Cache-Control recipes that actually work
Choose response directives by whether data is public, how long staleness is acceptable, and whether a stored response may be reused without validation.
Use long freshness for files whose URL changes with their contents, validation for HTML, and explicit privacy rules for personalized responses. Put Cache-Control on the response. A cache policy is part of your deployment and data model: decide which versions may coexist before choosing the numbers.
Pick a recipe
These durations are example budgets, not universal defaults. All times are seconds.
| Response | Cache-Control | What it prevents |
|---|---|---|
| Hashed JS, CSS, images | public, max-age=31536000, immutable |
Repeat downloads and unnecessary validation while fresh |
| HTML entry point | no-cache plus an ETag |
Reusing old HTML without checking the origin |
| Personalized API, briefly reusable | private, max-age=30, stale-while-revalidate=30 |
Shared-cache reuse; some blocking refreshes |
| Sensitive response that must not be stored | no-store |
Storage by compliant HTTP caches |
| Public API behind a CDN | public, max-age=0, s-maxage=60 |
A full browser freshness window while allowing edge reuse |
private permits the browser’s private cache. It is not authentication or encryption. Never add public to user-specific content just to improve a hit ratio. A shared cache key that omits the user cannot be repaired by a short TTL.
Keep asset URLs immutable
For /assets/app.a83f2c.js, publish new bytes at a new hashed path. Keep old assets available for clients that still have old HTML. A year-long TTL is safe only if the path’s meaning never changes during that period. Configure missing-asset errors separately so a failed deployment does not cache a 404 for a year.
The immutable extension avoids revalidation while a stored response is fresh; it does not make a URL permanent or override expiration. Its semantics are specified in RFC 8246.
Validate HTML instead of forbidding storage
A typical response is:
Cache-Control: no-cache
ETag: "html-build-42"
Vary: Accept-Encoding
The next request can carry If-None-Match: "html-build-42". When that representation is unchanged, return a bodyless 304 Not Modified with the relevant validator and cache metadata. Generate validators from the actual representation; a constant ETag defeats updates. Strong validators must change when representation bytes change, including content coding where applicable.
Run this local example with Node 26. Save it as cache-demo.mjs, then run node cache-demo.mjs. Its validator is derived from the exact response bytes:
import { createServer } from 'node:http';
import { createHash } from 'node:crypto';
const body = Buffer.from('<!doctype html><title>Cache demo</title><p>Build 42</p>\n');
const etag = '"' + createHash('sha256').update(body).digest('hex') + '"';
createServer((req, res) => {
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('ETag', etag);
if (req.headers['if-none-match'] === etag) {
res.writeHead(304).end();
return;
}
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end(body);
}).listen(8788, '127.0.0.1');
In another terminal, capture the first response’s ETag and send it back:
curl -sS -D cache-headers.txt -o /dev/null http://127.0.0.1:8788/
cat cache-headers.txt
etag=$(awk 'tolower($1) == "etag:" { sub("\r$", "", $2); print $2 }' cache-headers.txt)
curl -sS -D - -o /dev/null http://127.0.0.1:8788/ \
-H "If-None-Match: $etag"
Output, trimmed to the status and cache headers from each response:
HTTP/1.1 200 OK
Cache-Control: no-cache
ETag: "439f63b6e2de6e2fff06adebfa95ebb9dc41795ea3a3c9a6cc29f98062d4253c"
HTTP/1.1 304 Not Modified
Cache-Control: no-cache
ETag: "439f63b6e2de6e2fff06adebfa95ebb9dc41795ea3a3c9a6cc29f98062d4253c"
This demo handles the single exact validator sent by these commands. Use your framework’s conditional-request handling for production, including validator lists, * and weak comparison for If-None-Match. Curl does not act as a browser HTTP cache here; these commands inspect revalidation without claiming that a CDN or browser stored anything. Stop the demo with Ctrl+C.
Bound staleness deliberately
With max-age=30, stale-while-revalidate=30, a supporting cache may serve a response fresh for 30 seconds, then reuse it for another 30 while revalidating asynchronously. This suits a dashboard summary better than an authorization decision. The extension is permission, not a background timer: traffic must trigger refresh, and unsupported caches may revalidate synchronously. See RFC 5861.
no-store does not purge copies previously stored under another policy. Change existing policies with an explicit cache invalidation plan. Service-worker Cache Storage and application state also need their own rules.
For CDN recipes, s-maxage overrides max-age for shared caches. Verify your provider’s configuration and inspect Age and provider cache-status headers across repeated requests. Vary must describe negotiated variants; it cannot substitute for correct privacy boundaries.
The core directives and validation rules come from RFC 9111. Go deeper into cache variants and keys.