Writing HTTP Caching Headers With LLMs in November 2026: Mark Personal Responses Private, Revalidate With ETags, and Fingerprint Static Files Before You Cache Them for a Year
Ask a coding assistant to "make the site faster with caching" and you will usually get a few lines that set Cache-Control: public, max-age=86400 on everything. That one line can make a page load instantly. It can also serve one customer's account page to another customer through a shared CDN, or leave users stuck on a broken JavaScript bundle for a day after you shipped the fix.
HTTP caching headers are short, but they are a contract between your server, every browser, and every proxy or CDN in between. LLMs are good at writing the syntax and weak at knowing which responses are personal, which files change, and what your CDN does by default. This guide walks through how to get correct caching code out of an assistant: classify your responses first, pick a header for each class, add revalidation with ETags, and test the result with real requests.
Cache-Control max-age works like a date printed on a carton: until it passes, a cache may hand out the copy it already has without asking. Image: Expiration date on a milk carton by .gershon.zippora, CC BY-SA 4.0, via Wikimedia Commons.
Why caching headers go wrong when generated
The common failure modes are predictable:
- One policy for every route. The model adds a global middleware that sets the same
max-ageon HTML, API responses, and static files. publicon personalized data. A response that depends on the session cookie gets markedpublic, so a shared cache is allowed to store it and hand it to the next visitor.- Long caching on unversioned files.
/app.jsgets a one-yearmax-age, and now there is no way to push an update to people who already have it. - Confusing
no-cachewithno-store.no-cachemeans "store it, but check with the server before using it".no-storemeans "do not keep a copy at all". Models swap them regularly. - Forgetting
Vary. The response changes by language or encoding, but the cache key does not, so users get the wrong variant.
None of these show up in a quick local test, because your own browser is the only cache involved. They show up in production, behind a CDN, with many users.
Step 1: Classify every response before asking for code
Before you prompt, list your routes and put each one into a bucket. This is the part only you can do, because the model cannot see which handlers read the session. A small table like this is enough:
- Fingerprinted static assets:
/assets/app.3f9a1c.js,/assets/site.8b2e.css, hashed images. The file name changes whenever the content changes. - Unversioned static files:
/favicon.ico,/robots.txt,/logo.pngreferenced by fixed URL. - Public HTML and public API data: marketing pages, blog posts, a public product catalog. Same for every visitor.
- Personalized responses: dashboards,
/api/me, cart contents, anything that reads a cookie or anAuthorizationheader. - Sensitive responses: account settings, billing details, exported reports, one-time tokens. Should not be written to disk anywhere.
Paste this classification into your prompt. A useful prompt looks like:
I'm adding HTTP caching headers to an Express app behind a CDN.
Here is every route and its class:
- /assets/* : fingerprinted by the build (hash in filename)
- /favicon.ico, /robots.txt : unversioned static
- /, /blog/:slug : public HTML, same for all visitors
- /api/products : public JSON
- /dashboard, /api/me, /api/cart : depend on the session cookie
- /account/billing, /api/export/:id : sensitive
Write middleware that sets Cache-Control per class.
Do not use a single global policy. Explain each directive you choose.
Add ETag-based revalidation for the public HTML and /api/products.
Asking the model to explain each directive is worth it: when it writes public next to /api/me, the explanation makes the mistake obvious.
Step 2: Pick a sensible header for each class
These are reasonable starting points. Adjust the numbers to how often your content really changes.
Fingerprinted assets: cache for a long time
Cache-Control: public, max-age=31536000, immutable
Because the URL changes whenever the file changes, the old URL's content never needs to update. One year is the conventional maximum. immutable tells browsers that support it not to revalidate even when the user reloads. This is only safe if your build really puts a content hash in the filename. Check your build output before you let a model apply this to a whole directory.
Unversioned static files: short cache plus revalidation
Cache-Control: public, max-age=3600
An hour (or a day, for a favicon) keeps load down without trapping users on old content for long. Pair it with an ETag or Last-Modified so that after expiry the browser can get a cheap 304 Not Modified instead of the whole file.
Public HTML and public API data: revalidate, optionally let the CDN hold it
Cache-Control: public, no-cache
or, if you want a CDN to absorb traffic:
Cache-Control: public, max-age=0, s-maxage=300, stale-while-revalidate=60
The first version lets browsers store the page but forces a check with the server every time, which is cheap with ETags. The second keeps browsers revalidating while letting shared caches serve the page for five minutes (s-maxage only applies to shared caches) and serve a slightly stale copy for up to a minute while fetching a fresh one in the background. Support for stale-while-revalidate varies across CDNs, so confirm it in your provider's documentation rather than trusting the model's claim.
HTML is usually the file that points at your fingerprinted assets, so keep its cache short. If the HTML is cached for a day, users keep loading last week's bundle names, and the benefit of fingerprinting disappears.
Personalized responses: private only
Cache-Control: private, no-cache
private means only the user's own browser may store it; CDNs and proxies must not. no-cache makes the browser check with the server before reuse, so a logged-out user does not see stale personal data after pressing back. If the data is not sensitive and you want quick back-button navigation, private, max-age=60 is also defensible.
Sensitive responses: do not store
Cache-Control: no-store
Use this for billing pages, exports with personal data, and anything carrying a secret. Nothing else needs to be combined with it. You will often see models add Pragma: no-cache and Expires: 0 as well; those are for very old HTTP/1.0 caches and are harmless but not needed for modern clients.

Yesterday's paper is fine for some things and wrong for others. Caching is choosing, per response, how old a copy is still acceptable. Image: A stack of newspapers by Daniel R. Blume, CC BY-SA 2.0, via Wikimedia Commons.
Step 3: Add revalidation with ETags
An ETag is an identifier for a specific version of a response. The browser sends it back in If-None-Match, and if it still matches, the server replies 304 Not Modified with no body. This turns "always check with the server" into a cheap request.
Many frameworks already generate ETags. Express, for example, sets a weak ETag on res.send() responses by default, computed from the body. That saves bandwidth but not work: the server still builds the full page to hash it. For expensive pages, a better pattern is to derive the ETag from data you already have, such as a row's version number or updated_at timestamp, and check it before rendering:
app.get("/blog/:slug", async (req, res) => {
const meta = await db.posts.findMeta(req.params.slug); // id, updated_at only
if (!meta) return res.status(404).send("Not found");
const etag = `"post-${meta.id}-${meta.updated_at.getTime()}"`;
res.set("ETag", etag);
res.set("Cache-Control", "public, no-cache");
if (req.get("If-None-Match") === etag) {
return res.status(304).end();
}
const post = await db.posts.findFull(meta.id);
res.send(renderPost(post));
});
Things to check in what the model writes:
- The ETag must change whenever the output changes. If the page also shows a comment count or a sidebar from another table, a post-only version number is wrong. Either include those inputs in the tag or accept that part of the page can be briefly stale.
- Template or code changes. A deploy that changes the HTML layout does not change
updated_at. Including a build ID in the ETag fixes this. - ETags are quoted strings.
If-None-Matchcan also contain several comma-separated tags or*. A strict equality check is fine for a simple case; a library or framework helper handles the full syntax. - Weak versus strong. A
W/prefix marks a weak ETag, meaning "semantically equivalent" rather than byte-identical. Weak tags are fine for 304 checks on pages.
Last-Modified with If-Modified-Since works the same way at one-second resolution. It is simpler and good enough for files; ETags are more precise for database-backed content.
Step 4: Get Vary right
A cache stores responses keyed by URL. If your server returns different bodies for the same URL depending on a request header, the cache needs to know, or it will hand the wrong version to the next user. That is what Vary is for.
- If you compress responses,
Vary: Accept-Encodingis needed. Most compression middleware adds it automatically; check the actual response. - If you pick a language from
Accept-Language, addVary: Accept-Language, or better, put the language in the URL (/en/,/de/) so caches split naturally. - Avoid
Vary: Cookieas a way to make personalized pages "cacheable". Every user has a different cookie, so the shared cache fills with one-off copies, and many CDNs treat it as uncacheable anyway. Mark those responsesprivateinstead.
When a model suggests Vary: * or a long list of headers, ask it which ones actually change the body. Each extra header splits the cache further.
Step 5: Check what your CDN does with these headers
CDNs do not all follow origin headers the same way. Some ignore Cache-Control unless you enable it, some refuse to cache any response that carries Set-Cookie, and some cache only certain file extensions by default. Some have their own header (for example a CDN-specific cache-control header) that overrides the standard one for the edge only. An LLM's training data mixes many providers and old defaults, so treat its statements about your CDN as a hunch and confirm them in the current documentation.
Two specific things to verify:
- Responses with
Set-Cookieare not shared. If a public page also refreshes a session cookie, a shared cache that stores it could hand that cookie to other visitors. Either do not set cookies on public cacheable routes, or make sure your CDN strips or bypasses them. - Purging. If you use
s-maxage, know how to purge a URL or the whole cache after an urgent fix. Write the purge command into your runbook before you need it.
Step 6: Test with real requests
Do not judge caching by clicking around in your own browser. Use curl to see the actual headers and the revalidation behavior:
# See the caching headers on each class of route
curl -sI https://example.com/assets/app.3f9a1c.js | grep -i -E "cache-control|etag|vary|age"
curl -sI https://example.com/blog/hello | grep -i -E "cache-control|etag|vary|age"
curl -sI -H "Cookie: session=..." https://example.com/api/me | grep -i cache-control
# Confirm a 304 on revalidation
ETAG=$(curl -sI https://example.com/blog/hello | awk -F': ' 'tolower($1)=="etag"{print $2}' | tr -d '\r')
curl -s -o /dev/null -w "%{http_code}\n" -H "If-None-Match: $ETAG" https://example.com/blog/hello
The last command should print 304. Many CDNs also add a response header showing whether the edge served a hit or a miss, along with an Age header; look for those after a couple of repeated requests.
It is worth turning the most important checks into automated tests, because caching rules regress quietly when someone adds a route:
test("personal routes are never shared-cacheable", async () => {
for (const path of ["/dashboard", "/api/me", "/api/cart"]) {
const res = await request(app).get(path).set("Cookie", testSession);
const cc = res.headers["cache-control"] || "";
expect(cc).not.toMatch(/public/);
expect(cc).toMatch(/private|no-store/);
}
});
test("billing is no-store", async () => {
const res = await request(app).get("/account/billing").set("Cookie", testSession);
expect(res.headers["cache-control"]).toMatch(/no-store/);
});
A safer default helps too: have the middleware set private, no-cache on any response that did not explicitly choose a policy. Then a new route that nobody classified fails safe instead of being cached publicly.
A short review checklist for generated caching code
- Is there a separate policy per class of response, not one global header?
- Does anything that reads a cookie or
Authorizationheader saypublic? It should not. - Are long
max-agevalues used only on fingerprinted files? - Is HTML kept short-lived so it can point users at new asset names?
- Is
no-storeused for sensitive data, andno-cacheonly where revalidation is intended? - Do ETags change whenever the rendered output changes, including after deploys?
- Is
Varyset for compression and any header-based content negotiation? - Have you confirmed your CDN's behavior with cookies and origin headers in its current docs?
- Do you have tests that fail if a personal route becomes shared-cacheable?
Bottom line
An assistant can write correct caching headers in seconds once you tell it which responses are public, personal, sensitive, or versioned. Without that, it guesses, and its guess tends toward "cache everything", which is the one choice that can leak data. Classify your routes, give each class its own policy, use ETags so revalidation is cheap, and test with curl and automated checks before trusting the CDN in front of it.
Comments
Post a Comment