Node is excellent at handling JSON-out endpoints and bad at serving static files: every file read goes through the event loop, every byte copies through V8 buffers. Putting Nginx in front lets it own static assets (where it’s 10-50x faster than Node), terminate TLS, cache idempotent proxy responses, and apply rate limiting in front of the application. This walks through the production config — not a hello-world template, but the actual proxy_cache directives, cache-control headers, and operational tuning that makes the front-door earn its keep.
How to verify
Inspect the current cache behavior and headers:
curl -sI https://app.example.com/static/main.css | grep -E 'Cache|Expires|ETag|Age'
curl -sI https://app.example.com/api/things | grep -E 'X-Cache|Cache-Control'
ls -lh /var/cache/nginx/proxy_cache/
nginx -T | grep -E 'proxy_cache|proxy_pass|location' | head -40
sudo tail -20 /var/log/nginx/access.log
If the X-Cache-Status header you set up in Nginx returns MISS for every request to a cacheable endpoint, the cache directives are not being matched. Check the proxy_cache_valid and Vary headers.
What’s happening
Nginx as a reverse proxy with caching does two distinct things: it serves static files directly from disk (memory-mapped, sendfile-style — no Node hop), and it caches responses from the Node upstream when the response headers permit. The cache is on-disk in proxy_cache_path, indexed by the proxy_cache_key (URL by default, but you can include cookies or auth headers).
Cache validity is driven by the response’s Cache-Control header, the Expires header, or proxy_cache_valid directives that override on a per-status-code basis. The interesting feature is proxy_cache_lock: when many clients request the same uncached URL simultaneously, only one request reaches the upstream — the rest wait for the cached fill. That’s what protects Node from a stampede when a cache entry expires.
The procedure
-
Set up the cache directory and a cache zone in Nginx. Pick the path on a fast disk; Nginx is fine with thousands of files in one directory:
# /etc/nginx/conf.d/cache.conf proxy_cache_path /var/cache/nginx/proxy_cache levels=1:2 keys_zone=app_cache:50m max_size=10g inactive=24h use_temp_path=off; -
The server block fronting the Node app: terminate TLS, serve static directly, proxy /api to Node:
server { listen 443 ssl http2; server_name app.example.com; ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem; # Static files: serve from disk, never hit Node location /static/ { alias /srv/myapp/static/; expires 1y; add_header Cache-Control "public, immutable"; access_log off; } # API: proxy to Node, cache GETs location /api/ { 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; # Cache configuration proxy_cache app_cache; proxy_cache_methods GET HEAD; proxy_cache_key "$scheme$request_method$host$request_uri"; proxy_cache_valid 200 301 302 5m; proxy_cache_valid 404 1m; proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; proxy_cache_background_update on; proxy_cache_lock on; proxy_cache_lock_timeout 5s; proxy_cache_bypass $http_cache_control; proxy_no_cache $http_authorization; # never cache authenticated requests add_header X-Cache-Status $upstream_cache_status always; } } -
Set the right
Cache-Controlheaders from Node. Nginx caches based on what your app says is cacheable:app.get('/api/things', (req, res) => { res.set('Cache-Control', 'public, max-age=300, s-maxage=300'); res.json(things); }); -
For HTML responses that depend on auth state, use
Vary: Cookieto scope the cache key by the auth cookie. Or setCache-Control: privateand let only the browser cache, not Nginx:res.set('Cache-Control', 'private, no-store'); // don't cache at all -
Test the cache. First request should MISS, second should HIT, then after
proxy_cache_validexpires, EXPIRED:curl -sI https://app.example.com/api/things | grep X-Cache-Status # MISS curl -sI https://app.example.com/api/things | grep X-Cache-Status # HIT sleep 310 curl -sI https://app.example.com/api/things | grep X-Cache-Status # EXPIRED or MISS -
To purge a single URL, the open-source Nginx doesn’t have a built-in command. The two options: shell-out to remove the cache file (compute the key MD5), or install
ngx_cache_purgefrom Nginx Plus / a third-party module. The simpler answer is to wait outinactive=24hor restart Nginx with the cache cleared.
Common pitfalls
proxy_cache_lockrequiresproxy_cache_background_updateto be useful; without the latter, the lock just serializes refreshes and waiting clients see latency spikes at expiry.Cache-Control: public, max-age=300plus aSet-Cookieresponse header makes Nginx skip caching (cookies indicate per-user content). StripSet-Cookiein the Node response for cacheable endpoints, or explicitly includeproxy_ignore_headers Set-Cookie.X-Forwarded-Forfrom an untrusted client is a security issue: a malicious client can spoof its IP. Always rewrite, never append blindly, and setreal_ip_header+set_real_ip_fromfor your trusted upstream IPs.- Cache invalidation is hard. If your Node app emits content based on a Redis state, Nginx will serve the stale cached version after the Redis state changes — for up to
proxy_cache_valid. Either accept the staleness or bypass cache for the affected URLs. - Serving static files with
try_filesplus a Node fallback chains the worst of both. If/index.htmlexists on disk, Nginx serves it; if not, request goes to Node. Pick one ownership model per path.
For WebSocket scaling alongside this front-door, see WebSocket scaling patterns. In the engagements Stack Harbor runs, Nginx is the standard front-door — TLS, static, caching, rate limit — and we own its config as part of managed operations so application developers don’t have to debug proxy_cache_key mismatches under outage pressure.