My Next.js app runs on port 3000. I want https://example.com to proxy to it with the right client IP and WebSockets working for socket.io. What config do I need?
DEV3 Developer Forum
How do I put Nginx in front of a Node.js or Next.js app, including WebSocket support?
Ask a question
Every post is reviewed first. Usually reviewed within 24 hours.
dev3 ·
0
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
Hostlets the app build correct absolute URLs.X-Forwarded-For/X-Real-IPgive the visitor IP; without them every request looks like 127.0.0.1.X-Forwarded-Prototells the app the request was HTTPS. Express needsapp.set('trust proxy', 1)to use it; Next.js behind a proxy respects forwarded headers.UpgradeandConnectionare required for WebSockets. Withoutproxy_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