Why this matters
Precompressed delivery reduces CPU and latency; Vary ensures correct CDN caching.
Serve precompressed .br/.gz variants when the client sends Accept-Encoding, set "Vary: Accept-Encoding", and apply immutable caching for hashed assets; keep HTML revalidatable.
Precompressed delivery reduces CPU and latency; Vary ensures correct CDN caching.
Side-by-side examples engineers can pattern-match during review.
HttpServer::new(|| App::new().service(Files::new("/assets","./public"))) // no headersHttpServer::new(|| App::new().wrap_fn(|req, srv|{ / set Vary and Cache-Control based on path / srv.call(req) }).service(Files::new("/assets","./public"))res.insert_header(("Vary","Accept-Encoding"))Files::new("/assets","./public") // defaultsFrom 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).
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.