DEV3 Technologies home

DEV3 Developer Forum

How do I put Nginx in front of a Node.js or Next.js app, including WebSocket support?

DevOps helpSolved0 views

1 reply

dev3 · Accepted answer

Bind the app to localhost and let Nginx handle TLS and public traffic.

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 443 ssl;
    http2 on;
    server_name example.com;

    ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    client_max_body_size 20M;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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 Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 60s;
    }
}

(The map block goes in the http context, for example in conf.d/.) The standalone http2 on; directive needs Nginx 1.25.1 or newer. On older versions write listen 443 ssl http2; instead (newer versions still accept it but log a deprecation warning).

Why each header

  • Host lets the app build correct absolute URLs.
  • X-Forwarded-For / X-Real-IP give the visitor IP; without them every request looks like 127.0.0.1.
  • X-Forwarded-Proto tells the app the request was HTTPS. Express needs app.set('trust proxy', 1) to use it; Next.js behind a proxy respects forwarded headers.
  • Upgrade and Connection are required for WebSockets. Without proxy_http_version 1.1, upgrades fail with 400/502.

Long lived sockets may need a higher proxy_read_timeout (Nginx closes idle connections after 60 seconds by default), or application level pings.

Pitfalls

  • Do not expose port 3000 publicly; block it in the firewall.
  • Cache static assets: Next.js /_next/static/ is fingerprinted, so it is safe to cache with long expiry.
  • Reload with sudo nginx -t && sudo systemctl reload nginx.

Run the app under systemd or PM2 so it restarts automatically (see the systemd topic).

0

Your reply

Every post is reviewed by DEV3 before it appears. Usually reviewed within 24 hours.

Markdown supported. Use ``` for code blocks. Images are not allowed.