What is the Cache-Control header and what are its key directives?
Cache-Control is an HTTP response header that instructs browsers and intermediate caches (CDNs, proxies) how to store and serve a response.
Key directives:
max-age=N— cache the response for N seconds. After expiry the browser revalidates with the server.s-maxage=N— like max-age but only for shared caches (CDNs). Overrides max-age for CDNs.no-cache— don't serve from cache without revalidating with the server first (304 check). Despite the name, it does cache.no-store— never cache. Used for sensitive data (banking, personal health).immutable— tells the browser the resource will never change; don't revalidate even if max-age expires. Used with content-hashed filenames.stale-while-revalidate=N— serve stale for up to N seconds while fetching a fresh copy in the background.public— CDNs are allowed to cache.private— only the browser may cache (not CDNs).
# Content-hashed JS/CSS — cache forever, never revalidate
Cache-Control: public, max-age=31536000, immutable
# HTML — revalidate every request but serve stale instantly
Cache-Control: public, max-age=0, stale-while-revalidate=86400