Self-Hosting Next.js on a VPS with nginx

You do not need a platform-as-a-service to run a Next.js app in production. A single VPS, nginx, a TLS certificate and (optionally) Cloudflare in front will host a marketing site or a full server-rendered app just fine, as long as you pick the right output mode and do not accidentally cache dynamic HTML.

There are two honest paths:

  • A static export (output: 'export'), which is a folder of HTML, CSS and JS that nginx can serve on its own.
  • A Node server (output: 'standalone' or next start), which you run under systemd or PM2 and put nginx in front of as a reverse proxy.

This guide covers both, then adds Let’s Encrypt, cache headers and a sensible Cloudflare setup. It is written for a current Next.js App Router app on a Linux VPS (Ubuntu is assumed in the commands).

First: decide whether you need a Node server

Static export is simpler and cheaper to operate: there is no Node process to restart, no SSR CPU bill, and the origin can be a plain directory. It is the right default for a brochure site, a docs site, or a front end that talks only to a separate API.

It is the wrong choice as soon as you need anything that must run on the server at request time. Next.js documents these as unsupported with a static export: Server Actions, Incremental Static Regeneration, cookies, redirects and rewrites in next.config, proxy/middleware that reads the incoming request, Route Handlers that depend on the request, Draft Mode, and Image Optimization with the default loader. Dynamic routes also need generateStaticParams() so every path can be written to disk at build time.

A short way to decide:

You need… Use
HTML/CSS/JS only, plus a separate API Static export + nginx
Server Components that fetch at request time, Server Actions, auth cookies Node server (standalone)
ISR / on-demand revalidation Node server
next/image with the default optimizer Node server (or a custom loader on a static export)
The lowest possible ops burden Static export

If you are unsure, start with a static export and switch to standalone when you hit a feature the export cannot support. Switching later is a config and deploy change, not a rewrite. The same “build once, serve files” idea is also how many browser-only tools are shipped: the origin only serves assets.

Path 1: static export, served by nginx

Enable the export in next.config.ts (or .js):

import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  output: 'export',
  // Emits /about/index.html instead of /about.html, which is easier for nginx
  trailingSlash: true,
  images: {
    // The default optimizer needs a Node server. Disable it, or set a custom loader.
    unoptimized: true,
  },
};

export default nextConfig;

next build writes a folder named out/. With trailingSlash: true, routes become directories (/about/index.html), so nginx can use a simple try_files rule.

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /var/www/example/out;
    index index.html;

    location /_next/static/ {
        add_header Cache-Control "public, max-age=31536000, immutable";
        access_log off;
    }

    location / {
        try_files $uri $uri/ =404;
    }

    error_page 404 /404.html;
}

Hashed files under /_next/static/ can be cached for a year. HTML should not use that header: a new deploy must be visible on the next request.

NEXT_PUBLIC_* variables are inlined at build time. If a public API URL changes, you rebuild and re-upload out/. There is no server process to pick up a new .env.

Path 2: a standalone Node server

For anything that needs a server, use Next.js’s standalone output. The build traces only the files the app needs and writes a minimal server.js, so you do not install the full node_modules tree on the VPS.

import type { NextConfig } from 'next';

const nextConfig: NextConfig = {
  output: 'standalone',
};

export default nextConfig;

Build, then copy the two folders the standalone output does not include (Next.js leaves them out because a CDN often serves them):

npm ci
npm run build
cp -r public .next/standalone/
cp -r .next/static .next/standalone/.next/

The folder .next/standalone now contains server.js, a slim node_modules, public/ and .next/static/. That is what you rsync to the VPS, for example to /srv/nextjs/app.

Two build-time traps are worth naming:

  • NEXT_PUBLIC_* is still inlined at build time. Server-only variables (DATABASE_URL, secrets) can be provided at process start. Public ones cannot.
  • Build on the same OS and CPU architecture as the server. Image Optimization uses sharp, which ships native binaries. A build made on macOS or Windows will not process images correctly on a Linux VPS. Building on the VPS, or in CI on ubuntu-latest for an x86-64 server, avoids that.

Start it bound to localhost, never to the public interface:

cd /srv/nextjs/app
NODE_ENV=production PORT=3000 HOSTNAME=127.0.0.1 /usr/bin/node server.js

nginx will be the only thing that talks to the internet.

Run it under systemd (or PM2)

systemd is already on the VPS, restarts the process after a crash or reboot, and is enough for a single app.

# /etc/systemd/system/nextjs.service
[Unit]
Description=Next.js
After=network.target

[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/srv/nextjs/app
Environment=NODE_ENV=production
Environment=PORT=3000
Environment=HOSTNAME=127.0.0.1
EnvironmentFile=-/etc/nextjs/env
ExecStart=/usr/bin/node server.js
Restart=on-failure
RestartSec=5
TimeoutStopSec=30
NoNewPrivileges=yes
ProtectSystem=full
PrivateTmp=yes

# SIGTERM lets Next.js finish in-flight requests and `after()` callbacks
KillSignal=SIGTERM

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable --now nextjs
sudo systemctl status nextjs

TimeoutStopSec=30 gives Next.js time to finish in-flight requests and pending after() work on deploy or reboot.

PM2 is a reasonable alternative if you already use it, or if you want its log rotation and an easy cluster start:

cd /srv/nextjs/app
pm2 start server.js --name nextjs --env production
pm2 startup
pm2 save

If you run more than one Node instance, remember that Next.js’s default ISR cache lives on each instance’s local disk. They will not share invalidations unless you add a shared cache handler.

nginx as a reverse proxy

Do not expose port 3000. Put nginx in front: it terminates TLS, serves hashed static files without waking Node, and can reject oversized or malformed requests.

Streaming matters here. App Router responses (especially Flight / RSC payloads) can be streamed. If nginx buffers the whole body, time-to-first-byte gets worse and some streamed responses misbehave. Turn buffering off for the proxied location.

upstream nextjs {
    server 127.0.0.1:3000;
    keepalive 64;
}

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    # Temporary: certbot will upgrade this server to HTTPS
    location /.well-known/acme-challenge/ {
        root /var/www/certbot;
    }

    location / {
        return 301 https://example.com$request_uri;
    }
}

server {
    listen 443 ssl http2;
    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;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    # Hashed build assets: cache hard, skip Node
    location /_next/static/ {
        alias /srv/nextjs/app/.next/static/;
        add_header Cache-Control "public, max-age=31536000, immutable";
        access_log off;
    }

    location / {
        proxy_pass http://nextjs;
        proxy_http_version 1.1;
        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;
        proxy_set_header Connection        "";
        proxy_buffering off;
        proxy_read_timeout 60s;
    }
}

Point www at the same 443 block or, cleaner, a short server that 301s www to the apex. Keep the Node firewall closed: only 80 and 443 should be public.

Let’s Encrypt with certbot

Once nginx answers on port 80 for the domain:

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com

certbot obtains the certificate, writes the TLS paths into the server block, and installs a renew timer. Check it with sudo certbot renew --dry-run. Renewals need port 80 to stay open for the HTTP-01 challenge (or you can switch to DNS-01 if you prefer).

If Cloudflare is already proxying the domain (orange cloud), HTTP-01 against the origin can be awkward. Either complete the first certificate with the DNS record temporarily grey-clouded, use DNS-01, or install a Cloudflare Origin CA certificate on nginx and skip public Let’s Encrypt on the origin. The last option only works while Cloudflare is in front; a grey-cloud failover would not present a publicly trusted cert.

Cache headers, ISR and Cloudflare

Next.js already sets Cache-Control for you:

  • Fully prerendered pages are marked public, so a CDN may cache the HTML.
  • Pages that use dynamic APIs are marked private, so the HTML must not be cached at the edge.

Honour those headers. The failure mode to avoid is a Cloudflare “Cache Everything” rule (or an nginx expires on /) that stores a personalised or cookie-dependent page and serves it to the next visitor.

A practical split:

  • /_next/static/*: cache for a long time at nginx and at Cloudflare. The filenames change when the content changes.
  • /_next/image: let Next.js handle it if you use the default optimizer. Do not layer a second aggressive cache unless you understand the image cache TTL.
  • HTML for a static export: a short CDN TTL (minutes, not days), or bypass the cache and rely on the origin. You can purge on deploy if you prefer a longer TTL.
  • HTML for a Node app: respect Cache-Control. Do not force-cache all HTML.

ISR and the server cache live on the Node machine’s disk by default. Cloudflare sitting in front does not replace that cache, and it cannot revalidate a tag inside Next.js. If you purge Cloudflare after an ISR revalidation, you are only clearing the edge; the origin still decides what to render.

Cloudflare in front

A typical setup is: registrar or Cloudflare DNS, an A record for the VPS, proxy enabled, and SSL/TLS set to Full (strict). Full (strict) means Cloudflare talks to nginx over HTTPS and verifies a valid certificate (Let’s Encrypt or a Cloudflare Origin CA). “Flexible” encrypts only the browser-to-Cloudflare hop and leaves the origin in HTTP; it is also a reliable way to get redirect loops once nginx itself redirects to HTTPS.

Other settings that matter for Next.js:

  • Leave Rocket Loader off. Injecting a script loader in front of your bundles is a common cause of hydration errors.
  • Be conservative with auto-minifying JavaScript at the edge. Your production build is already minified.
  • If you use WebSockets (uncommon for a Next.js origin, more common for other apps on the same box), make sure the proxy upgrade headers are intact.
  • Cloudflare Bot Fight Mode and aggressive challenge rules can interfere with preview deployments or webhook callbacks. Allowlist any server-to-server paths you rely on.

None of this requires a paid plan for a single site. The paid features (more cache rules, WAF customisation) are optional.

A deploy you can repeat

A boring, reliable loop looks like this:

  1. Build in CI on Linux, or on the VPS if it has enough RAM. next build uses much more memory than server.js at runtime. If the kernel kills the build, add swap or build elsewhere and upload the artefact.
  2. rsync .next/standalone/ (already containing public and .next/static) to a new directory on the server, then flip a symlink to /srv/nextjs/app.
  3. sudo systemctl restart nextjs (or pm2 restart nextjs).
  4. If you cache HTML at Cloudflare, purge those URLs (or the zone) after the process is healthy.
  5. Hit / and one dynamic route, and confirm the certificate is valid.

For a static export, skip systemd and rsync out/ over the previous document root.

That is the whole production path: pick static or Node, put nginx in front, terminate TLS, cache only what is safe, and let Cloudflare be a CDN and DDoS layer rather than a second application server. If you are also writing the React app itself, Building Scalable React Applications with TypeScript covers the structure that makes those deploys uneventful. And if you want a team to handle the Next.js app, the server and the surrounding SEO work, MakeWorking does that kind of web development. For a project brief, you can also get in touch.

Muhammad Jawad Iqbal Khan

A full-stack web, mobile and automation developer. Hire me

Need help deploying a web app?

I can help you build and self-host web apps, including Next.js, nginx, TLS and a production-ready setup.