This tutorial walk you through how do we build and deploy the application to the cPanel which is developed by Next.Js. The Next.js gives you the best experience for the develop with all the features for production environment like, hybrid static & server rendering, TypeScript support and more. The configuration part is not needed.

I hope, you already have purchased the cPanel hosting and registered a domain name. Here, I have used the domain name: thelinuxfaq.com for the explanation and I used Ubuntu machine. Let's jump into the steps directly.

The step one, clone the source code from the Git or any other repository to your local machine. If the code is already available in your local machine that's great. The source code directory "next-app"

Before build the Next.js application we need to make few changes in your package.json file.  that, have to add the two lines in your package.json file those are homepage and export and also see the screenshot below,


$ cd next-app
$ vim package.json

 
"homepage": "https://www.thelinuxfaq.com",
"export": "next export",



Next, open your terminal window and execute the commands below,
$ npm run build && npm run export

You may received the errors,

> next build
sh: 1: next: not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! sanbrix@0.1.0 build: `next build`
npm ERR! spawn ENOENT
npm ERR! 
npm ERR! Failed at the sanbrix@0.1.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
npm ERR! A complete log of this run can be found in:

So, execute the command below to install modules,
$ npm install

 then run the commands again,
$ npm run build && npm run export


hopefully, now the build successfully generated and we should get a new directory as out in our current location, then, compress the files/directories which are available in "out" directory using zip or tar command, dot (.) is indicate to current location. 
‚Äč$ zip -r  next-app.zip 


Login to your cPanel account and upload the zipped file to the File Section > File manger > public_html

Now, remove the old files and extract the zipped file in your root path  /home/yourname/public_html/

Finally, let’s create .htaccess in public_html with following code,

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ — [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]

Save the files and close it. Now run the nextJs app from the browser https://thelinuxfaq.com/