PortGate

Blueprints · Node.js & Next.js

Production 25 min · Nginx / systemd

Next.js production self-host with middleware header guard

Runs a standalone Next.js server as a dedicated user. Nginx clears x-middleware-subrequest before the request reaches the app and caches hashed static files.

Live config

Baked-in protections

Step 1 · ini

Service user and unit

/etc/systemd/system/next.service

standalone output uses server.js. Build with output: standalone before enabling the unit.

[Unit]
Description=Next.js app.example.com
After=network.target

[Service]
User=next
Group=next
WorkingDirectory=/var/www/next
ExecStart=/usr/bin/node /var/www/next/server.js
Environment=NODE_ENV=production
Environment=PORT=3000
Environment=HOSTNAME=127.0.0.1
Restart=always
NoNewPrivileges=true
PrivateTmp=true
ProtectSystem=strict
ReadWritePaths=/var/www/next

[Install]
WantedBy=multi-user.target

Step 2 · nginx

Nginx proxy

/etc/nginx/sites-available/app.example.com.conf

The empty middleware header is intentional. Do not copy an attack value into this line.

server {
    listen 443 ssl;
    http2 on;
    server_name app.example.com;
    server_tokens off;
    ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;

    location /_next/static/ {
        proxy_pass http://127.0.0.1:3000;
        proxy_set_header Host $host;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }

    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header x-middleware-subrequest "";
    }
}

Step 3 · bash

Enable the service

/root/portgate-blueprints/next-enable.sh

Creates the user, then reloads systemd and Nginx.

#!/bin/sh
set -eu
id "next" >/dev/null 2>&1 || useradd --system --create-home --shell /usr/sbin/nologin "next"
install -d -m 755 -o "next" -g "next" "/var/www/next"
systemctl daemon-reload
systemctl enable next.service
systemctl restart next.service || echo "Next.js did not start. Confirm the standalone server.js build exists."
ln -sfn "/etc/nginx/sites-available/app.example.com.conf" /etc/nginx/sites-enabled/app.example.com.conf
nginx -t
systemctl reload nginx