Deploying a Next.js application on your own server
From source code to a service that runs, restarts itself and updates without downtime: build, process manager, reverse proxy, HTTPS, backups and rollback. No platform, on an ordinary Linux machine.
Deploying to a managed platform is simple, and often the right choice. Deploying to your own machine requires understanding what the platform was doing for you — which is exactly the point of the exercise.
Here is the full chain, as I set it up, with the reasoning for each step and the traps I hit.
What you need first
- A Linux machine with administrative access. A small virtual server is plenty for one site.
- Node.js installed, in a version your application supports.
- A domain name whose DNS records you control.
- Nginx, or another reverse proxy.
One piece of advice before anything else: do not run the application as root. Create a dedicated user. If the application is compromised, the attacker inherits its rights — better that they are thin.
1. Build
npm ci # installs exactly the lock file, not "roughly" it
npm run build
npm ci rather than npm install: the former installs locked versions and fails if the lock file is inconsistent, the latter may update dependencies. In production you want reproducibility — the same command should produce the same result in six months.
The trap of build-time variables
This is the mistake that wastes the most time, and it is silent.
Some environment variables are read at build time and frozen into the generated pages. A canonical URL, an analytics identifier, an API prefix: if you change them in the environment file and restart the application, nothing changes. The pages were generated with the old value.
You have to rebuild. If a URL is wrong after a domain migration, this is almost always why.
The rule: anything embedded in static HTML is frozen at build. Anything read at request time can change with a restart. Know which category each variable falls into.
2. Keep the process running
next start launches a Node server. If the terminal closes, it dies. If the machine reboots, it does not come back. If the process crashes at three in the morning, it stays dead until somebody notices.
You need a process manager. I use PM2; systemd does the same job and is already installed.
// ecosystem.config.js
module.exports = {
apps: [
{
name: "mysite",
script: "node_modules/next/dist/bin/next",
args: "start --port 3000",
cwd: "/var/www/mysite",
// IMPORTANT: a single process, in fork mode.
// This application uses SQLite, which does not support
// several processes writing to the same file.
// Switching to cluster mode would corrupt the database.
exec_mode: "fork",
instances: 1,
max_memory_restart: "512M",
env: { NODE_ENV: "production" },
error_file: "/var/log/mysite/error.log",
out_file: "/var/log/mysite/out.log",
time: true,
},
],
};
pm2 start ecosystem.config.js
pm2 save # rewrites the list restored at boot
pm2 startup # prints the command to enable it
Careful if the machine hosts other sites
On a server shared between projects, some commands are destructive well beyond your application:
pm2 delete all # deletes EVERY application, not only yours
pm2 restart all # restarts everything, other people's sites included
pm2 kill # stops the whole daemon
Get into the habit of naming your application explicitly: pm2 restart mysite. And of reading pm2 list before any global command.
3. Put a reverse proxy in front
The application listens on 127.0.0.1:3000, so only from the machine itself. Nginx receives public traffic, terminates TLS, serves static files and forwards the rest.
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location /_next/static/ {
alias /var/www/mysite/.next/static/;
expires 1y;
add_header Cache-Control "public, immutable";
}
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
And always test before reloading:
sudo nginx -t && sudo systemctl reload nginx
On a machine hosting several sites, reloading an invalid configuration breaks all of them. The && is the protection.
4. HTTPS
Let's Encrypt issues free certificates, valid for three months, renewed automatically.
sudo certbot certonly --webroot -w /var/www/certbot -d example.com -d www.example.com
I use certonly --webroot rather than the plugin that edits Nginx by itself. On a shared machine I would rather nothing rewrote a configuration I have not read — least of all one serving other sites.
Check that automatic renewal works, without waiting for expiry:
sudo certbot renew --dry-run
5. The files that must never be overwritten
This is the most important point in this article, and the easiest to neglect.
An application in production has two categories of files:
- Code, which comes from the repository and is replaced on every deployment.
- Runtime state, which is created by the application while it runs and exists nowhere else.
Runtime state is typically the database and uploaded files. It must live outside anything a deployment touches, and it must be backed up.
/var/www/mysite/
.next/ ← regenerated on every build
node_modules/ ← regenerated
src/ ← comes from the repository
data/app.db ← STATE: back it up, never commit it
public/uploads/ ← STATE: back it up, never commit it
The public/ and uploads trap
I hit this one for real, and it deserves a paragraph.
Next.js scans the public/ directory at build time and serves only what it found there. A file written into public/uploads/ while the application runs — so any upload made through an admin interface — returns 404 until the next build.
The symptom is disorienting: the file is on disk, the right size, perfectly valid, and the server answers 404.
The fix is not to rebuild on every upload. It is to serve those files through a route that reads the disk per request, or to let Nginx serve them directly with an alias. In both cases, remember to refuse paths that escape the directory, and to serve only the extensions you write yourself.
6. Deploying an update
cd /var/www/mysite
git pull
npm ci
npm run build
pm2 reload mysite # reload, not restart: no downtime
pm2 reload replaces the process gracefully. In-flight requests finish.
If you have database migrations, they apply after the build and before the reload — and a backup is taken before all of it:
sqlite3 data/app.db ".backup 'data/pre-deploy.db'"
npx prisma migrate deploy
pm2 reload mysite
7. Knowing how to go back
A deployment without a way back is a bet. The bare minimum:
# Before: record the deployed revision
git rev-parse HEAD > /var/www/mysite/.previous-version
# After, if it goes badly
git checkout "$(cat .previous-version)"
npm ci && npm run build
pm2 reload mysite
Careful: a database migration does not replay backwards so easily. If the migration dropped a column, returning to the previous code does not bring it back. That is why the pre-deployment backup is not optional.
Hardening the machine, the minimum
A server exposed on the Internet is probed constantly, within minutes of going online. It is not a targeted attack, it is background noise. A few measures remove most of it.
Disable SSH password authentication. This is the highest-value measure, by a long way.
# /etc/ssh/sshd_config
PasswordAuthentication no
PermitRootLogin prohibit-password
Verify your key works in a second session before reloading the service. Locking yourself out is a classic, and the server will not take your word for it.
Expose only what must be exposed.
sudo ufw default deny incoming
sudo ufw allow 22/tcp
sudo ufw allow 80,443/tcp
sudo ufw enable
# Check what actually listens, IPv4 AND IPv6
ss -tlnp
That last point deserves emphasis: a ufw rule covers both families, but hand-written iptables rules protect IPv4 only. A database listening on :: while you filtered only IPv4 is exposed to the whole world.
Apply security updates automatically. On Debian and Ubuntu, unattended-upgrades installs security fixes without intervention. The risk of an update breaking something is real but far smaller than that of a known vulnerability left open for months.
Verifying the deployment actually worked
A deployment that finishes without errors is not a successful deployment. Three checks, every time:
# 1. The application responds, and so do its dependencies
curl -fsS https://example.com/api/health | jq .
# 2. Key pages return 200, not a disguised 500
for u in / /services /journal /contact; do
printf "%-12s %s\n" "$u" "$(curl -s -o /dev/null -w '%{http_code}' "https://example.com$u")"
done
# 3. No errors appeared since the reload
pm2 logs mysite --lines 50 --nostream | grep -i error
And one check no command will do for you: open the site in a real browser, on the real domain name. Some failures — an over-strict content security policy, a blocked resource, a script that throws — are completely invisible from the command line, because curl reads neither policies nor JavaScript.
8. Monitoring
A successful deployment is not the end of the work.
- A health endpoint the application exposes, which actually checks what it depends on — the database, for instance — not merely that a process answers.
- External monitoring calling that endpoint from outside. A system monitoring itself does not report its own outage.
- Readable logs, with rotation so they do not fill the disk.
- An alert on disk space. A full disk is a mundane, predictable failure that breaks everything: the database cannot write, neither can the logs, and backups produce empty files.
Recap
- Build with
npm ci && npm run build— knowing which variables are frozen at build time. - Run under a process manager, with automatic restart.
- Put a reverse proxy in front, application on the loopback.
- HTTPS with automatic renewal, tested in dry-run mode.
- Keep runtime state out of the code path, and back it up.
- Deploy with
reload, notrestart. - Have a written rollback procedure.
- Monitor from outside.
It is no more complicated than a managed platform. It is simply explicit: every step is a decision you make, instead of a behaviour you inherit. And on the day something breaks, you know where to look.
Tags
- Next.js
- Linux
- Nginx
- Deployment