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 -yWe'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 npmnpm i -g n # installs `n` globallyn lts # or "latest"node -vWe 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 nginxnginx -vCreate a nginx config file:
sudo nano /etc/nginx/sites-available/<your-app-name>.confNow 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/ # verifysudo service nginx restart # cus of config changesThis 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 repocd nextjs-app # or your cloned reponpm iSetup env variables and stuff here if necessary before building:
npm run buildnpm run startWithout 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 pm2cd /var/www/<your-app-name>pm2 start npm --name “<app-name>” -- startpm2 startuppm2 saveYou 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.