Common Nginx Error Log Pattern (Next.js / Node.js)
When upstream sockets, timeouts, body limits, or Docker DNS rules are misconfigured for Next.js / Node.js, Nginx typically records an entry matching the log line below inside /var/log/nginx/error.log:
2026/11/22 14:22:18 [error] 1842#1842: *914 upstream prematurely closed connection while reading response header from upstream, client: 203.0.113.42, server: app.example.com, request: "GET /dashboard HTTP/2.0", upstream: "http://127.0.0.1:3000/dashboard", host: "app.example.com"
Reverse Proxy Architecture & Header Forwarding for Next.js / Node.js
Self-hosting a Next.js App Router application behind Nginx on a Linux VPS or container host gives you predictable pricing and full infrastructure control, but Next.js expects specific HTTP/1.1 proxy behavior that default Nginx boilerplate omits. Your Next.js server listens on http://127.0.0.1:3000 (via next start, standalone output, or PM2), while Nginx terminates TLS on port 443, compresses responses, and forwards client identity headers so Server Actions and authentication callbacks construct accurate HTTPS URLs.
Next.js App Router relies heavily on React Server Components streaming, Suspense boundaries, and Route Handlers that stream AI completions or Server-Sent Events. By default, Nginx buffers upstream responses internally before flushing bytes to the browser, which stalls React Suspense streaming and makes incremental UI chunks appear all at once after the entire render finishes. Configuring clean HTTP/1.1 keepalives, appropriate proxy_read_timeout ceilings, and disabling proxy_buffering on streaming routes preserves sub-second Time to First Byte.
Equally important are static asset caching and Server Action origin verification. Because Next.js fingerprints every bundle inside /_next/static/* with content hashes, serving or caching that path with immutable 1-year Cache-Control headers removes massive load from Node.js. Meanwhile, Next.js 14/15+ validates the Origin header against Host and X-Forwarded-Host on every Server Action POST; if Nginx strips or alters Host or X-Forwarded-Proto, Server Actions fail immediately with HTTP 403 or "Invalid Server Actions request."
Before cutting over DNS for a self-hosted Next.js deployment, inspect both /var/log/nginx/error.log and your Next.js stdout logs while submitting a Server Action, navigating client-side routes, and loading a Suspense-streamed page. Confirming HTTP/2 TLS termination, intact X-Forwarded-Proto: https headers, and sufficient client_max_body_size for Server Action file uploads guarantees production parity with managed edge platforms.
For zero-downtime Next.js production rollouts behind Nginx, combine PM2 cluster reload or blue-green Docker deployments with explicit proxy_connect_timeout and proxy_next_upstream directives so brief Node.js restarts never surface raw 502 Bad Gateway pages to active users. Monitoring both Nginx access timing ($upstream_response_time) and Next.js server memory consumption helps catch uncached SSR bottlenecks early, while keeping /_next/static/ off the Node.js event loop lets a single modest VPS serve thousands of concurrent App Router visitors reliably.
Step-by-Step Nginx & Next.js / Node.js Deployment Guide
Apply the Nginx server block above alongside these upstream framework trust-proxy settings so HTTPS detection, real client IPs, and reload safety work reliably in production.
1Run Next.js Production Server Bound to Localhost Only
ecosystem.config.cjs (PM2 / systemd)Bind next start to 127.0.0.1:3000 so port 3000 is never exposed directly to the public internet bypassing Nginx TLS and rate limits. Use output: "standalone" in next.config.ts for minimal memory footprints.
ecosystem.config.cjs (PM2 / systemd)bashmodule.exports = { apps: [ { name: 'nextjs-app', script: 'node_modules/next/dist/bin/next', args: 'start -H 127.0.0.1 -p 3000', env: { NODE_ENV: 'production', PORT: 3000, }, }, ], };2Add Immutable Caching for /_next/static/ and Streaming Headers in Nginx
/etc/nginx/sites-available/app.example.com.confAdd a dedicated location /_next/static/ block inside your HTTPS server block so content-hashed JS and CSS assets cache aggressively, and forward Host, X-Forwarded-Host, and X-Forwarded-Proto intact for Server Actions.
/etc/nginx/sites-available/app.example.com.confnginxlocation /_next/static/ { proxy_pass http://127.0.0.1:3000; add_header Cache-Control "public, max-age=31536000, immutable"; } location /api/stream { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_buffering off; proxy_cache off; proxy_read_timeout 300s; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; }3Allow Server Action Body Size and Trusted Proxied Origins in Next.js
next.config.tsSynchronize Next.js Server Action body limits with Nginx client_max_body_size (default 1 MB in both Nginx and Next.js) and configure allowedOrigins if reverse proxies rewrite hostnames.
next.config.tstypescriptimport type { NextConfig } from 'next'; const nextConfig: NextConfig = { output: 'standalone', experimental: { serverActions: { bodySizeLimit: '10mb', allowedOrigins: ['app.example.com'], }, }, }; export default nextConfig;4Enable the Site, Issue Certbot SSL, and Reload Nginx Safely
terminal (Ubuntu / Debian)Symlink the configuration into sites-enabled, validate Nginx syntax before reloading, and provision auto-renewing Let's Encrypt certificates with Certbot.
terminal (Ubuntu / Debian)bashsudo ln -s /etc/nginx/sites-available/app.example.com.conf /etc/nginx/sites-enabled/ sudo certbot --nginx -d app.example.com sudo nginx -t && sudo systemctl reload nginx
Common Next.js / Node.js Nginx Reverse Proxy Pitfalls
Review these three production failure modes before reloading Nginx on staging or live servers.
Nginx proxy_buffering Stalling React Suspense and AI Streaming Routes
Nginx buffers upstream responses in 4KB–8KB chunks by default. On Next.js streaming Route Handlers or Server Components using Suspense, buffering holds the entire stream until completion unless you set proxy_buffering off; (or emit X-Accel-Buffering: no from Next.js).
Server Actions Failing With "x-forwarded-host header does not match origin"
Next.js compares the browser Origin header against Host and X-Forwarded-Host to stop CSRF attacks on Server Actions. If Nginx omits proxy_set_header Host $host; or sets X-Forwarded-Host to an internal upstream name like 127.0.0.1:3000, every Server Action POST fails.
Caching HTML Pages Alongside /_next/static/ Bundles
Applying long expires or proxy_cache directives to the root location / caches stale SSR HTML referencing deleted chunk hashes from previous deployments, causing ChunkLoadError crashes in user browsers. Only set immutable caching on /_next/static/.
Complete Your Deployment With Matching Docker Compose & CORS Tools
Pair this Nginx reverse proxy block with healthcheck-gated Docker Compose orchestration and verified browser CORS headers:
Generate a Docker Compose config for Next.js App Router standalone output with Prisma ORM and PostgreSQL 16 using pg_isready healthchecks and service DNS.
Configure CORS for Next.js App Router Route Handlers serving external SPAs or widgets. Fix 405 OPTIONS preflights, next.config.ts headers, and Vary: Origin.
Frequently Asked Questions
- Do I need WebSocket Upgrade headers for Next.js in production behind Nginx?
- Standard production Next.js SSR does not require WebSockets unless you attach a custom WebSocket server or real-time channel. However, keeping HTTP/1.1 Upgrade and Connection $connection_upgrade configured guarantees zero breakage for custom socket endpoints and staging HMR servers.
- Why do Next.js image optimization requests (/_next/image) return 502 or 504 behind Nginx?
- Next.js sharp image resizing fetches remote source images synchronously on first request. If remote fetches take longer than Nginx's default 60s timeout or if outbound DNS fails inside Docker, Nginx logs 504 Gateway Timeout. Raising proxy_read_timeout to 120s and verifying outbound container DNS resolves this.
- Should I let Nginx or Next.js handle Gzip compression?
- Handle Gzip (or Brotli) in Nginx and set compress: false inside next.config.ts. Offloading compression from the single-threaded Node.js event loop to Nginx's C-level workers reduces Node CPU usage and prevents double-compression overhead.
- Why did my Next.js file upload return 413 Request Entity Too Large even after raising bodySizeLimit?
- Both Nginx and Next.js enforce independent 1 MB defaults. Even if you raise serverActions.bodySizeLimit to 10mb in next.config.ts, Nginx rejects the request before it ever reaches Node.js unless client_max_body_size 10M; is set in your Nginx server block.
Related Nginx Reverse Proxy Guides
Browse all 10 Nginx guides →Nginx Reverse Proxy Config for Node.js Express & PM2 (trust proxy & SSL)
Generate a production Nginx reverse proxy for Node.js Express and PM2 on port 4000 with trust proxy, real client IP headers, Certbot SSL, and rate-limit safety.
Nginx Config for React (Vite) SPA + Same-Origin /api/ Proxy (Zero CORS)
Serve a built React Vite dist/ SPA at / with try_files history fallback while proxying /api/ to your backend on the same Nginx domain to eliminate CORS.
Nginx Reverse Proxy for Docker Compose Services (127.0.0.11 DNS Resolver)
Prevent 502 Bad Gateway and Nginx startup crashes in Docker Compose using resolver 127.0.0.11 and variable proxy_pass for dynamic container restarts.
Nginx Multi-Service Subpath Routing Config (/api/, /auth/ & /ws/)
Route /api/, /auth/, and /ws/ microservices to separate backend ports under one Nginx HTTPS domain. Master trailing-slash prefix stripping and prevent 404s.