Why this matters
Differentiating asset types ensures fast repeat loads while keeping documents revalidatable.
In Express, use serve-static with setHeaders to apply "Cache-Control: public, max-age=31536000, immutable" for files matching /\.[0-9a-f]{8,}\./ and "Cache-Control: no-cache" for HTML. Also set correct Content-Type.
Differentiating asset types ensures fast repeat loads while keeping documents revalidatable.
Side-by-side examples engineers can pattern-match during review.
app.use(express.static('public')); // default headers, no hashing awarenessapp.use(express.static('public', { setHeaders:(res, path)=>{ if(/\.[0-9a-f]{8,}\./.test(path)){ res.setHeader('Cache-Control','public, max-age=31536000, immutable'); } else if(path.endsWith('.html')){ res.setHeader('Cache-Control','no-cache'); } } }));res.setHeader('Cache-Control','public, max-age=31536000, immutable')app.use(express.static('public')) // no Cache-ControlFrom the same buckets as this rule.
All static JS/CSS/font/image files MUST use content-hashed filenames (e.g., app.9c1a7b.js) and be served with "Cache-Control: public, max-age=31536000, immutable". HTML and other non-fingerprinted documents MUST be served with "Cache-Control: no-cache" (or equivalent) to enable conditional revalidation.
Serve text-based assets (JS, CSS, JSON, SVG) with Brotli (br) when the client sends "Accept-Encoding: br" and fallback to gzip. Always set "Vary: Accept-Encoding" and do NOT compress already-compressed formats (e.g., .png, .jpg, .woff2).