Web Performance · HTTP · Cloudflare · Backend

HTTP Caching Headers Explained: Cache-Control, ETag and stale-while-revalidate

A practical guide to HTTP caching: Cache-Control directives, no-cache vs no-store, ETag and 304 responses, s-maxage for CDNs, stale-while-revalidate and the Vary header.

Sander Yazıcıoğlu Published: 4 min read Türkçe oku

HTTP Caching Headers Explained: Cache-Control, ETag and stale-while-revalidate

Most "the site still shows the old version" tickets I have dealt with, on corporate client sites and on internal tools alike, came down to one wrong header. HTTP caching is simple once the vocabulary clicks, and it is one of the cheapest performance wins there is: a response that never leaves the browser cache is the fastest request possible. This guide explains the headers I actually set and why.

Two questions every cache asks

A browser or CDN that holds a stored response asks:

  1. Is it still fresh? If yes, use it without contacting the server. Cache-Control: max-age answers this.
  2. If it is stale, has it changed? Ask the server with a conditional request. ETag and Last-Modified answer this.

Freshness saves the whole request. Revalidation saves the body but still costs a round trip.

Cache-Control directives that matter

DirectiveMeaning
max-age=NFresh for N seconds in any cache
s-maxage=NOverrides max-age for shared caches (CDNs, proxies) only
no-cacheMay be stored, but must be revalidated before every use
no-storeMust not be stored anywhere
privateOnly the browser may store it, not a CDN
publicShared caches may store it, even for authenticated requests
immutableWill never change; don't revalidate even on reload
stale-while-revalidate=NServe stale for up to N seconds while refreshing in the background

The most common mistake is reading no-cache as "don't cache". It means "always check first". If you really mean don't store, for example a page with personal or banking data, use no-store.

A policy by resource type

This is the setup I use on Vite-built sites, including this one:

# Hashed assets: the file name changes when the content does
/assets/*        Cache-Control: public, max-age=31536000, immutable

# HTML: always check, so a deploy is visible immediately
HTML pages       Cache-Control: public, max-age=0, must-revalidate

# Images without hashes: short freshness, then revalidate
/images/*        Cache-Control: public, max-age=86400, stale-while-revalidate=604800

# Personalised API responses
/api/me          Cache-Control: private, no-cache

The reasoning: HTML is the entry point that references the hashed assets, so it must be fresh. Once the HTML is fresh, every asset URL it references is either already cached forever or new. How to apply these on Cloudflare Pages with a _headers file is shown in static site plus edge logic.

ETag and 304 Not Modified

An ETag is a fingerprint of the response. The browser sends it back as If-None-Match; if it still matches, the server answers 304 with no body.

GET /api/projects/42
If-None-Match: "a1b2c3"

HTTP/1.1 304 Not Modified
ETag: "a1b2c3"
Cache-Control: private, no-cache

Express generates weak ETags for res.send bodies by default. For an API where computing the body is the expensive part, compute the ETag from something cheap, such as a version column or updated_at, and short-circuit before building the response:

app.get('/api/projects/:id', async (req, res) => {
  const meta = await db.projectVersion(req.params.id); // cheap query
  const etag = `"p${meta.id}-v${meta.version}"`;
  res.setHeader('ETag', etag);
  res.setHeader('Cache-Control', 'private, no-cache');
  if (req.headers['if-none-match'] === etag) return res.status(304).end();
  res.json(await db.projectWithRelations(req.params.id)); // expensive query
});

On large dashboards this saves both bandwidth and the heavy query. It complements a server-side cache like the ones in Redis caching patterns; it doesn't replace one.

stale-while-revalidate

max-age=60, stale-while-revalidate=600 means: for one minute serve from cache; for the next ten minutes still serve from cache instantly, but refresh in the background. Users never wait on the revalidation. It suits content where being a minute or two behind is fine, such as blog listings, public stats or images. Browser and CDN support varies, so treat it as an optimisation, not a guarantee.

The Vary header

Vary tells caches which request headers change the response. Vary: Accept-Encoding is normal and keeps gzip and Brotli copies apart. Be careful with:

  • Vary: Cookie effectively disables shared caching, since every visitor's cookies differ.
  • Vary: User-Agent fragments the cache into thousands of copies.

If you serve different languages from one URL, Vary: Accept-Language is needed, but separate URLs per language are better for caching and SEO alike; see hreflang for multilingual sites.

Debugging

Check the real headers rather than trusting config:

curl -sI https://example.com/assets/index-D0z6elPr.js | grep -i -E 'cache-control|etag|age|cf-cache-status'

On Cloudflare, cf-cache-status tells you what the edge did: HIT, MISS, EXPIRED, REVALIDATED, or DYNAMIC (not eligible for caching). The Age header shows how long a response has sat in a shared cache. In Chrome DevTools, the Network panel's Size column shows "(disk cache)" or "(memory cache)" for responses that never hit the network.

Conclusion

Give hashed assets a year and immutable, make HTML revalidate on every load, use private and no-cache with ETags for personalised API data, and reserve no-store for truly sensitive responses. Add stale-while-revalidate where slightly old content is acceptable, keep Vary minimal, and verify everything with curl -I.

All articles →