Skip to content

Caching static assets and proxy responses with Nginx in front of Node.js

Put Nginx in front of Node.js for static-asset serving, proxy response caching, and offloading TLS — with cache-control discipline that matches your app.

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

  1. 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;
  2. 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;
      }
    }
  3. Set the right Cache-Control headers 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);
    });
  4. For HTML responses that depend on auth state, use Vary: Cookie to scope the cache key by the auth cookie. Or set Cache-Control: private and let only the browser cache, not Nginx:

    res.set('Cache-Control', 'private, no-store');  // don't cache at all
  5. Test the cache. First request should MISS, second should HIT, then after proxy_cache_valid expires, 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
  6. 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_purge from Nginx Plus / a third-party module. The simpler answer is to wait out inactive=24h or restart Nginx with the cache cleared.

Common pitfalls

  • proxy_cache_lock requires proxy_cache_background_update to be useful; without the latter, the lock just serializes refreshes and waiting clients see latency spikes at expiry.
  • Cache-Control: public, max-age=300 plus a Set-Cookie response header makes Nginx skip caching (cookies indicate per-user content). Strip Set-Cookie in the Node response for cacheable endpoints, or explicitly include proxy_ignore_headers Set-Cookie.
  • X-Forwarded-For from an untrusted client is a security issue: a malicious client can spoof its IP. Always rewrite, never append blindly, and set real_ip_header + set_real_ip_from for 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_files plus a Node fallback chains the worst of both. If /index.html exists 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.