Why this matters
Brotli significantly reduces transfer sizes for text assets and the Vary header prevents cache poisoning across clients.
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).
Brotli significantly reduces transfer sizes for text assets and the Vary header prevents cache poisoning across clients.
Side-by-side examples engineers can pattern-match during review.
GET /img/logo.png
200 OK
Content-Encoding: gzip
/ double-compressing a PNG increases size and latency /GET /app.9c1a7b.js
200 OK
Content-Encoding: br
Vary: Accept-Encoding
/ optimal compression with correct cache variation /Content-Encoding: br
Vary: Accept-EncodingContent-Encoding: gzip
/ for .png /From 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.
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.