[TUTORIAL] How to deploy a NextJS website on CyberPanel

This tutorial assumes you know how to create a website with CyberPanel and you way around LiteSpeed/OLS WebAdmin Console.

Deploying a static build / Single-Page Application (SPA)

  1. Create a new website 2 - Creating Website e.g. for mynextjs.com
  2. Build your static export Deploying: Static Exports | Next.js
  3. Upload your out folder into your document root e.g. /home/mynextjs.com/public_html/
  4. Fix permissions in your file manager and visit the website at mynextjs.com

This kind of export has some limitations as described by NextJS Deploying: Static Exports | Next.js

Deploying a dynamic website / Server-side Rendering (SSR) Application or CSR Application

  1. Create a new website 2 - Creating Website e.g. for mynextjs.com
  2. Build your application API Reference: Next.js CLI | Next.js
  3. Setup your Node Environment:

Step 1: Install NodeJS from Os recommended repositories

$ yum install nodejs
## or
$ dnf install nodejs
## or
$ apt install nodejs

Step 2: Install Node.js version management

Install as described here Deploy nodejs app doesn'nt work - #2 by josephgodwinke OR simply

$ sudo npm cache clean -f
$ sudo npm install -g n
$ sudo n latest
## skip this part for almalinux/centos/rockylinux
$ sudo apt-get install --reinstall nodejs
## exit console and start new one or
$ sudo reboot
$ node -v

Step 3: Setup AppServer Context to Serve NextJS Application

Follow this step in the tutorial here Setup Express.js Application on CyberPanel/OpenLiteSpeed

Step 4: Change custom binary path of context

Go to https://SERVER_IP:7080/index.php and login with WebAdmin Console admin username and password.

Choose Virtual Hosts https://SERVER_IP:7080/index.php#view/confMgr.php?m=vh and click on the domain that represents the nextjs app e.g. mynextjs.com

Click on the context tab and edit App Server

Change Custom Binary Path to where your preferred node version is installed e.g.

$ whereis node
> node: /usr/bin/node /usr/local/bin/node /usr/share/node /usr/share/man/man1/node.1.gz
$ /usr/local/bin/node -v
> v16.20.1
$ /usr/bin/node -v
> v10.24.0
## now choose which one to use - I go with latest /usr/local/bin/node

Click on perform a graceful restart to restart lsws service.

Step 5: Configure and Deploy NextJS app with PM2

$ pm2 init simple
$ pm2 start ecosystem.config.js
## daemonize your app
$ pm2 startup && pm2 save
## to see all your node apps
$ pm2 list
## Display all apps logs in realtime
## https://pm2.keymetrics.io/docs/usage/process-management/
$ pm2 monit 

Now visit your website at mynextjs.com

to be continued