How To Install and Host Next.js With cPanel


Get the latest articles delivered to your inbox. No spam, unsubscribe anytime.
If you're developing Next.js web applications, you might be considering what options are available for hosting. Is it really necessary to host in the Cloud or can you host on traditional Shared or VPS hosting solutions?
Surprisingly, I found that Shared and VPS hosting services offer a great way to install and host applications using Next.js with cPanel.
In this article I'll show how to easily install and host a Next.js application on a Shared hosting provider, including:
Most websites and blogs these days are usually PHP based sites that use Shared or VPS hosting plans.
Since Next.js is a React based framework it requires a Node.js environment to run and host a React based web application. The good news is that most Shared and VPS hosting services support Node.js these days.
There's a lot of advantages to using traditional hosting, including:
Next.js is a highly performant framework for building next generation web applications and can serve static or server side rendered HTML payloads in most cases making it highly optimal for SEO performance and ranking.
For this article, you need access to the following:
The first step is to create a new Node.js application using the cPanel Node.js Application Manager.
> Tools > Software sectionexample.com placeholder to illustrate how to use an actual registered domain name and also replace username with your actual username.
Here's some details on what these fields are used for.
process.env.NODE_ENV that a Node.js might use for configuration./home/username/example.com./blog will append to the domain as example.com/blog. This will be the url to access the new application.server.js for now because we're going to create this file in following section. This will be the file that Node.js will execute when starting your application.Press the Create button to create the application. The new application will now show in Web Applications tab.
Now, let's create a Next.js application that we can use to install and run.
Let's create the application locally and then we'll zip it up and upload it to the remote server under the directory we designated in the Application root setting in the previous section.
Run the following command in a terminal to generate a new Next.js application.
1npx create-next-app@latest
Currently the create-next-app@latest is at version 14.x.x and requires at least Node.js v18.17 or later
It will prompt for some user input. Let's give it a project name of demo-app for now. Just accept all of the remaining prompts using defaults for now or select the options you prefer.
1What is your project named? demo-app2Would you like to use TypeScript? No / Yes3Would you like to use ESLint? No / Yes4Would you like to use Tailwind CSS? No / Yes5Would you like to use `src/` directory? No / Yes6Would you like to use App Router? (recommended) No / Yes7Would you like to customize the default import alias (@/*)? No / Yes8What import alias would you like configured? @/*
Once this completes, the Next.js application will be ready and there will be a new directory demo-app with the following contents.
1# This content is likely to change depending on generator version23├── .eslint.json4├── .gitignore5├── app6├── next-env.d.ts7├── next.config.mjs8├── node_modules9├── package.json10├── package-lock.json11├── postcss.config.js12├── public13├── README.md14├── tailwind.config.ts15└── tsconfig.json
As I mentioned earlier, we'll need to add a startup.js file in the root of the project directory.
The Node.js application in cPanel will execute this file to start the server.
It's recommended not to use package.json script tasks to start and stop the Node.js server.
Using a server.js file gives that control over to the Node.js Application Manager to start and stop the application.
You can think of it as running Node.js the traditional way.
1node server.js
To create the startup.js file enter the following command inside the demo-app directory.
1touch server.js
Copy this custom server code into the server.js file and save it.
This is the recommended sample code from the Next.js team. You can further customize it as needed but this is usually sufficient.
1const { createServer } = require('http')2const { parse } = require('url')3const next = require('next')45const dev = process.env.NODE_ENV !== 'production'6const hostname = 'localhost'7const port = 30008// when using middleware `hostname` and `port` must be provided below9const app = next({ dev, hostname, port })10const handle = app.getRequestHandler()1112app.prepare().then(() => {13 createServer(async (req, res) => {14 try {15 // Be sure to pass `true` as the second argument to `url.parse`.16 // This tells it to parse the query portion of the URL.17 const parsedUrl = parse(req.url, true)18 const { pathname, query } = parsedUrl1920 if (pathname === '/a') {21 await app.render(req, res, '/a', query)22 } else if (pathname === '/b') {23 await app.render(req, res, '/b', query)24 } else {25 await handle(req, res, parsedUrl)26 }27 } catch (err) {28 console.error('Error occurred handling', req.url, err)29 res.statusCode = 50030 res.end('internal server error')31 }32 })33 .once('error', (err) => {34 console.error(err)35 process.exit(1)36 })37 .listen(port, () => {38 console.log(`> Ready on http://${hostname}:${port}`)39 })40});
You'll find it's easier to just check this file into your code repo and just make sure to always include it when deploying.
The first thing to do is build the Next.js application
1cd demo-app23npm run build
This will create an optimized build for a production deployment and create a new directory named .next which is were all of the bundled code is located.
Once the build is done, we'll need to upload the files to the remote server.
You could use a utility like FileZilla or SFTP if you prefer. For this step, I'm just going to zip up the contents and use cPanel File Manager to move the files.
Here are the only resources we'll need to upload to the remote server:
1├── .next2├── next.config.mjs3├── package.json4├── package-lock.json5├── public6└── server.js
There's no need to include node_modules since we'll need to run the install process once the code is uploaded on the remote server.
You can use whatever utility for compressing the files. I'm just using the built-in compression tool in Mac to select and zip these files.

Now, just upload the zip (or tar) file to the /home/username/example.com directory on the remote server.
As a good practice, it's always best to stop your Node.js application in the Node.js Application Manager if it's running and restart it after a successful install.
Also, you'll want to make sure the directory is empty before deploying new content.
As you rollout and deploy more changes, it's a good practice to make a backup of the previous contents of this directory for a rollback restore point if there are any unforseen issues.
Example of a rollback zip/tar file demo-app--rollback-4-4-2024.zipExtract the new content into the clean Application root directory /home/username/example.com.
The directory should now have the following content.
1└── example.com2 ├── .next3 ├── next.config.mjs4 ├── package.json5 ├── package-lock.json6 ├── public7 └── server.js
Now, the npm install can be ran so all of the node_modules are available. There's a couple options on how to run this command.
Node.js Application Manager interfaceYou can run the install process in the cPanel Node.js Application Manager interface by clicking the Edit link. You'll see the following screen to start the install process.

I highly recommend running npm install from the command line using an SSH configured connection to your remote server.
If your hosting provider is running CloudLinux Node.js, you'll need to run the following command to activate the nodeenv for the session. This just makes sure the npm command is available in your SSH session terminal.
Just replace the username and example.com with your account details.
SSH terminal session
1# activate the `nodeenv`2source /home/username/nodevenv/example.com/18/bin/activate && cd /home/username/example.com
TheNode.js Application Managerinterface provides a copy link on theEditpage for these commands to activatenodeenv.
Now you can use npm commands as you normally do on your local development.
1npm install
Just for reference I'm including some additional npm install flags that you might need to use at times if the install hangs or fails.
At a bare minimum I always run npm install --omit=optional since certain binaries are usually blocked by networks for security reasons.
1# Does not install optionalDependencies like large binaries2# that are usually blocked by networks from downloading and can3# cause the npm install process to hang and timeout.4npm install --omit=optional56# Installs the dependencies regardless of the peerDependencies.7# Sometimes this is necessary when using higer versions of Node.js8# and the peerDependencies "engines" settings do not match.9# You'll get errors.10npm install --legacy-peer-deps1112# Installs the dependencies by force, similar to --legacy-peer-deps.13npm install --force
It's very important to get a successful npm install before proceeding, otherwise you may see "Module not found issues" or you won't be able to start your application successfully.
Now that the code has been deployed and all the packages are now installed, we are ready to start up the application.
On the Edit page of Node.js Application Manager interface, you'll see the start button.

Once the application starts, open a new browser window and point to your domain url and you will see the running demo-app Next.js application.
That's it! Pretty easy to get your Next.js applications up and running on Shared or VPS hosting services.
Some hosting providers use CloudLinux behind the scenes to virtually manage all of the Node.js applications in cPanel. This section will cover some details about the nodeenv environment when using command line, such as:
nodeenv manages different Node versions.nodeenv manages node_modules.package.json and package-lock.json referenced.Hopefully this section will help to avoid any downtime because of deployment issues. By following some basic guidelines, you'll be able to easily deploy with confidence.
Since these environments are usually virtual, running NPM processes is not like normal NPM operations on local environments.
When we ran the following command earlier to link and activate the nodeenv when using a SSH to do the npm install, it does a couple things behind the scenes worth mentioning.
If you follow the source path, it links to the nodeenv directory under the /home/username directory, where cPanel Node.js adds all of the Node.js and npm executables.
username: Your account usernameexample.com: This is the path to your Application root we set earlier when creating a Node.js application.1source /home/username/nodevenv/example.com/18/bin/activate && cd /home/username/example.com
Since we've set the Node.js version to v18.18.2 when we created the application earlier, it will do the following:
version folder (i.e. example.com/18).bin binaries.lib which is where node_modules is actually located.Since we only created one nodeenv for Node.js version 18, we should see the following.
1└── nodeenv2 └── example.com3 └── 184 ├── bin5 │ ├── activate6 │ ├── node7 │ ├── npm8 │ └── set_env_vars.py9 └── lib #lib directory10 ├── node_modules (link)11 ├── package.json (link /home/username/example.com/package.json)12 └── package-lock.json (link /home/username/example.com/package-lock.json)
After running the npm install process, you'll see that it added a node_modules symlink to the application root directory /home/username/example.com.
It also added symlinks to the package.json and package-lock.json files.
1└── example.com2 ├── .next3 ├── next.config.mjs4 ├── node_modules (link ~/nodevenv/example.com/18/lib/node_modules)5 ├── package.json6 ├── package-lock.json7 ├── public8 └── server.js
One thing to keep in mind is that everytime you run the npm install command it will reestablish this linking.
As most Javascript Node.js developers know, sometimes you may need to remove the node_modules and reinstall for various reasons. The best place to do this is in the lib directory.
To avoid any downtime, here's a few suggestions when running the install process:
node_modules unless absolutely necessary since it can be quite large and use up metered system bandwidth resources to reinstall.package-lock.json that is in sync with the package.json when deploying new changes.package.json, this way the install process will only update whats needed.As a general rule of thumb and to avoid any issues, I recommend to follow some simple guidelines.
1└── nodeenv2 └── example.com3 └── 184 ├── bin5 └── lib
npm install after any changes to reinstall and reestablish the symlinks to node_modules.Trying to remove thenode_modulesymlink in the actualApplication rootdirectory is not the same and will just break the link and leave your application without a way to resolve npm modules.
So if you keep these basic guidelines in mind, you should have a great experience setting up multiple Node.js apps running Next.js under one domain or subdomains if needed.
I hope this article has provided some useful information on how to host Next.js applications using traditional hosting providers. Moving to a cloud platform is really going to be based on your application and business requirements.
The other aspect is that you would need a fair amount of DevOps and Cloud Engineering experience to even setup all of the services needed, where a traditional hosting solution is quickly manageable using cPanel.
So there will be some tradeoffs here and there but at least you have some alternative options.


