from aryan: most guides i found online weren't helpful for me, hope this helps tho :)
ssh root@<server-ip-address>
Optional but recommended:
sudo apt update && sudo apt upgrade -y
We're installing NodeJS using a NodeJS version manager called n
. Feel free to use n
, nvm
, or fnm
(or just manually installing nodejs
on its own)
apt install npm
npm i -g n # installs `n` globally
n lts # or "latest"
node -v
We use nginx
as our web server to do one main thing, to re-route all traffic from our server-ip-address
to our localhost:3000
that's running our Next.js app.
apt install nginx
nginx -v
Create a nginx
config file:
sudo nano /etc/nginx/sites-available/<your-app-name>.conf
Now paste the following into the <your-app-name>.conf
file we created:
server {
listen 80;
server_name insert-your-vps-ip-address-here;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Let's create a symbolic link between this config file we created so we can have the same file in two places:
sudo ln -s /etc/nginx/sites-available/<your-app-name>.conf /etc/nginx/sites-enabled/
ls -la /etc/nginx/sites-enabled/ # verify
sudo service nginx restart # cus of config changes
This is where we'll store our Next.js apps so nginx
can see them:
cd /var/www/
Create or clone your app in here. I'm gonna create a new Next.js app with T3 stack for example here:
npm create t3-app nextjs-app # or git clone repo
cd nextjs-app # or your cloned repo
npm i
Setup env
variables and stuff here if necessary before building:
npm run build
npm run start
Without pm2
, you’d have to always a terminal running with npm run start
. With pm2
, you can run your Next.js or any node app as a background service - and will ensure your app re-runs on reboot and crashes as well.
cd ~
npm i -g pm2
cd /var/www/<your-app-name>
pm2 start npm --name “<app-name>” -- start
pm2 startup
pm2 save
You should now see your app if you head to server-ip-address
on your browser!
After successfully deploying your Next.js app on a VPS, you can enhance it further:
-
Easy Editing: SSH into the VPS using VS Code's extension that lets you edit code directly.
-
PM2: Consider using PM2 to have automatic restarts when your server dies (plus more features).
-
GitHub Actions: Set up CI/CD workflows to automatically deploy to your VPS.
@hungnv1312 Yes it works with app router (RSCs & server actions), tested it with the latest version of Next.js as of now (v14.2)