Netlify 10 ๐ Fine-Grained Caching & Cache API โ Mastering Cache-Control, Stale-While-Revalidate (SWR), cache tags, and on-demand invalidation
Netlify’s CDN has a default caching behaviour that is deliberately conservative: HTML and static assets are served with public, max-age=0, must-revalidate plus a strong ETag, which means the edge holds a copy but revalidates it against the current deploy on every request. That default is why a deploy becomes visible instantly across the world โ and it is also why the CDN cannot absorb a traffic spike on a dynamic route without a round trip to the origin on each request.
Fine-grained caching is the set of controls that let you override that default in a targeted way. A Cache-Control header decides whether the browser may reuse a response without asking. A Netlify-CDN-Cache-Control header decides whether Netlify’s edge may do the same, independently of the browser. stale-while-revalidate allows the edge to answer from an expired copy while it refreshes that copy in the background. Cache tags label the stored entries so a single API call can invalidate a chosen subset instead of everything. And the Web Cache API inside Edge Functions gives you explicit programmatic control when a header alone is not enough.
This chapter walks through the header layer first โ the two caches, the directives that address each, and the mechanism for narrowing a cache key. It then covers stale-while-revalidate and the trade-off it encodes, before turning to cache tags, the purge endpoint, and the caches.default object in Edge Functions.
Key point: Netlify maintains two independent caches โ the browser’s and its own edge โ and Cache-Control addresses the first while Netlify-CDN-Cache-Control addresses the second; cache tags turn invalidation from a site-wide purge into a targeted operation, but they can only evict the edge copy, never the copy already sitting in a visitor’s browser.
Why X exists
The revalidation cost problem. The safe default of must-revalidate on every response is correct but expensive at scale: a page that receives ten thousand requests a minute generates ten thousand conditional requests, and each one has to be answered by the edge re-reading the deploy artifact. Caching controls exist so that a response known to be stable for a defined window can be reused without that round trip.
The dynamic HTML problem. Statically generated assets rarely change, so their caching story is simple. Pages produced by functions, on-demand builders, or per-user logic change constantly, and marking them immutable breaks personalisation while marking them uncacheable destroys performance. stale-while-revalidate exists to occupy the middle ground: serve an old copy instantly and refresh it off the critical path.
The whole-site purge problem. Without granular invalidation, the only way to make a cached page reflect new content is to purge everything, which throws away every still-valid entry and forces a cold cache across the entire site. A content change to one product should evict one product’s cached responses, not all of them.
The cache poisoning problem. A cache key that ignores what a response depends on will store a personalised page under a shared key and hand it to the next visitor. A cache key that is too broad will never hit. The varying controls exist so that the key can be widened by exactly as much as the response actually depends on.
The two-audience problem. A browser and an edge have different needs. A browser should probably keep a page for a minute; the edge, which fronts thousands of browsers, can safely keep it for a day. A single max-age cannot express both, which is why Netlify provides a CDN-specific header that overrides the value the browser receives.
The function cost problem. A function that renders the same marketing page for every visitor burns invocations on identical work. Caching its response at the edge โ by returning a Cache-Control header from the function itself โ converts repeated invocations into repeated cache hits.
The trade-off. Every caching improvement trades freshness for speed, and the arithmetic is unforgiving: a max-age of one day means a content correction is invisible for up to a day on the edge and, worse, for up to a day in browsers you cannot purge. The controls exist to make that window explicit and as small as the workload allows.
a. The two caches and the directives that address them
Netlify’s response to any request can carry two cache-control headers. Cache-Control is the standard one: it governs both the browser and the edge, and it is the header that leaves your server and ends up in the visitor’s browser. Netlify-CDN-Cache-Control is Netlify-specific: it is consumed by the edge and stripped before the response reaches the client. When both are present, the CDN header wins at the edge while the standard header continues to govern the browser.
# netlify.toml โ the edge keeps a page for a day, the browser for a minute
[[headers]]
for = "/products/*"
[headers.values]
Cache-Control = "public, max-age=60, must-revalidate"
Netlify-CDN-Cache-Control = "public, max-age=86400, stale-while-revalidate=604800"
The practical consequence is that the CDN header is where you do the aggressive caching and the standard header is where you keep the browser on a short leash. A visitor who reloads sees a copy at most sixty seconds old; the edge absorbs everything in between. Reversing the relationship โ a long browser max-age with a short CDN window โ produces the worst of both: users stuck on stale content that you cannot evict.
# Static, fingerprinted bundles can be cached hard in both places
[[headers]]
for = "/assets/*"
[headers.values]
Cache-Control = "public, max-age=31536000, immutable"
The immutable directive is worth using only when the filename changes whenever the content does. Applied to a stable path such as /assets/app.js, it tells the browser never to revalidate for a year, so a corrected file at the same path is invisible until the cache is cleared manually.
The other half of the key is what the response varies on. By default the edge keys a cached response on the path and the query string. Netlify-Vary lets you add cookies or request headers to that key, or narrow the query string so that irrelevant parameters do not fragment the cache.
# Widen the key: the response depends on a session cookie
[[headers]]
for = "/account/*"
[headers.values]
Netlify-Vary = "cookie=session"
Cache-Control = "private, max-age=0, must-revalidate"
# Narrow the key: only these query parameters matter
[[headers]]
for = "/search"
[headers.values]
Netlify-Vary = "query=color,size"
Cache-Control = "public, max-age=300"
The first case fixes a correctness bug: without the cookie in the key, one user’s account page would be served to another. The second fixes a hit-rate bug: a page that only reads color and size should not get a separate cache entry for every utm_* tracking parameter that lands on it. Getting either wrong in the wrong direction is a real incident โ too narrow leaks data, too wide produces a cache that never hits.
Responses marked private or no-store are never stored by the edge at all, which is the correct setting for anything derived from an authenticated session.
b. Stale-while-revalidate and the freshness window
stale-while-revalidate defines a second window after max-age expires, during which the edge may serve the expired copy immediately and refresh it in the background. It is the directive that makes a long CDN cache safe for content that changes: visitors stop waiting for the refresh, and the refresh happens once rather than once per request.
# Fresh for 10 minutes, then served stale for an hour while refreshing
[[headers]]
for = "/blog/*"
[headers.values]
Netlify-CDN-Cache-Control = "public, max-age=600, stale-while-revalidate=3600"
Cache-Control = "public, max-age=0, must-revalidate"
Reading that rule aloud is the clearest way to understand it. For the first ten minutes every request is a plain cache hit with no revalidation. Between ten minutes and seventy minutes, the first request after expiry gets the stale copy instantly and triggers a single background revalidation; subsequent requests during that refresh get whatever is in the cache at that moment. After seventy minutes the response is genuinely stale and the next request has to wait for the origin. If the origin fails during the background refresh, the stale copy keeps being served, which makes the directive a crude availability mechanism as well as a performance one.
# A price feed that tolerates seconds of staleness but not minutes
[[headers]]
for = "/api/prices"
[headers.values]
Netlify-CDN-Cache-Control = "public, max-age=5, stale-while-revalidate=30, stale-if-error=86400"
stale-if-error is the companion directive and worth distinguishing: it governs how long an expired copy may be served when the revalidation attempt fails outright. It does not affect the normal path, only the failure path.
The same headers work on function responses. A Netlify Function that returns Cache-Control and Netlify-CDN-Cache-Control participates in the durable cache โ the edge stores the function’s output and serves it under the declared window, so the function is invoked on a cache miss rather than on every request.
// A function whose output is cached at the edge for an hour
export default async () => {
const data = await fetch("https://api.example.com/stats").then((r) => r.json());
return new Response(JSON.stringify(data), {
headers: {
"content-type": "application/json",
// Browser: short window, so a reload feels live
"cache-control": "public, max-age=30",
// Edge: an hour fresh, a day of stale tolerance
"netlify-cdn-cache-control": "public, max-age=3600, stale-while-revalidate=86400",
// Label the entry so it can be purged by tag later
"netlify-cache-tag": "stats",
},
});
};
The purge cannot reach the browser. A visitor who received max-age=30 keeps that copy for thirty seconds no matter what you do at the edge, which is why the browser window on anything you might need to correct urgently should be small or zero-with-revalidation.
c. Cache tags, purging, and the Cache API
A cache tag is a label attached to a stored response. Attach one with the Netlify-Cache-Tag response header, comma-separating multiple tags, and thereafter a single API call invalidates every entry carrying that tag across the whole site.
# Tag static product pages so one purge can evict all of them
[[headers]]
for = "/products/*"
[headers.values]
Netlify-CDN-Cache-Control = "public, max-age=86400, stale-while-revalidate=604800"
Netlify-Cache-Tag = "products"
// Tag by entity so a single product can be evicted on its own
const tag = `product-${product.id}`;
return new Response(html, {
headers: {
"content-type": "text/html",
"netlify-cdn-cache-control": "public, max-age=86400",
"netlify-cache-tag": `products,${tag}`,
},
});
The composite tag in that example is the pattern worth internalising: every product page carries the shared products tag and its own product-42 tag. A catalogue-wide change purges products; a single price correction purges product-42 and leaves the other thousand entries warm.
Purging is an authenticated API call. It requires a personal access token and the site’s ID, and it names the tags to evict.
# Evict every cached response tagged with this product
curl -X POST "https://api.netlify.com/api/v1/purge" \
-H "Authorization: Bearer $NETLIFY_TOKEN" \
-H "Content-Type: application/json" \
-d '{"site_id":"$SITE_ID","cache_tags":["product-42"]}'
Wire that call into the CMS webhook or the after-deploy step that knows what changed. The tag chosen at render time and the tag chosen at purge time have to agree exactly โ a typo in either produces a silent no-op, which is the most common failure mode of the whole mechanism, because a purge that matches nothing still returns success.
When headers are not expressive enough, an Edge Function can address the cache directly through the standard Web Cache API. caches.default exposes match, put, and delete, keyed by a Request, which gives you complete control over what is stored and under which key.
// Edge Function with manual cache control
export default async (request: Request) => {
const cache = caches.default;
const key = new Request(new URL(request.url).toString(), request);
// A cache match returns the stored response or undefined
const hit = await cache.match(key);
if (hit) return hit;
// Miss: build the response and store it explicitly
const origin = await fetch("https://backend.example.com/data");
const response = new Response(origin.body, {
headers: {
"content-type": "application/json",
// cache.put() only stores responses with a positive max-age
"cache-control": "public, max-age=600",
},
});
await cache.put(key, response.clone());
return response;
};
Two constraints govern cache.put. The response must carry a max-age or s-maxage greater than zero, and private, no-store, or Vary: * prevents storage; a response that fails these is silently not stored, so the function keeps working but never hits. Clone the response before storing it, because the body is a stream and can only be consumed once.
Complete Example Session
// ============================================
// PART 1: THE DEFAULT YOU ARE OVERRIDING
// ============================================
# Netlify serves HTML and assets with:
# cache-control: public, max-age=0, must-revalidate
# etag: "abc123"
# The edge keeps a copy, the browser revalidates it.
# Every deploy is therefore visible immediately.
// ============================================
// PART 2: A LONG BROWSER WINDOW ON FINGERPRINTED ASSETS
// ============================================
# netlify.toml
[[headers]]
for = "/assets/*"
[headers.values]
Cache-Control = "public, max-age=31536000, immutable"
// ============================================
// PART 3: SPLIT THE BROWSER AND EDGE WINDOWS
// ============================================
[[headers]]
for = "/products/*"
[headers.values]
Cache-Control = "public, max-age=60, must-revalidate"
Netlify-CDN-Cache-Control = "public, max-age=86400"
// ============================================
// PART 4: ADD STALE-WHILE-REVALIDATE
// ============================================
[[headers]]
for = "/blog/*"
[headers.values]
Netlify-CDN-Cache-Control = "public, max-age=600, stale-while-revalidate=3600, stale-if-error=86400"
Cache-Control = "public, max-age=0, must-revalidate"
// ============================================
// PART 5: NARROW THE KEY ON A SEARCH PAGE
// ============================================
[[headers]]
for = "/search"
[headers.values]
Netlify-Vary = "query=color,size"
Cache-Control = "public, max-age=300"
// ============================================
// PART 6: WIDEN THE KEY ON AN ACCOUNT PAGE
// ============================================
[[headers]]
for = "/account/*"
[headers.values]
Netlify-Vary = "cookie=session"
Cache-Control = "private, max-age=0, must-revalidate"
// ============================================
// PART 7: TAG THE CACHED ENTRIES
// ============================================
[[headers]]
for = "/products/*"
[headers.values]
Netlify-Cache-Tag = "products"
// ============================================
// PART 8: CACHE A FUNCTION RESPONSE AT THE EDGE
// ============================================
// netlify/functions/stats.ts
export default async () => {
const data = await fetch("https://api.example.com/stats").then((r) => r.json());
return new Response(JSON.stringify(data), {
headers: {
"content-type": "application/json",
"cache-control": "public, max-age=30",
"netlify-cdn-cache-control": "public, max-age=3600",
"netlify-cache-tag": "stats",
},
});
};
// ============================================
// PART 9: MANUAL CONTROL IN AN EDGE FUNCTION
// ============================================
// netlify/edge-functions/feed.ts
export default async (request: Request) => {
const cache = caches.default;
const key = new Request(request.url, request);
const hit = await cache.match(key);
if (hit) return hit;
const upstream = await fetch("https://backend.example.com/feed");
const response = new Response(upstream.body, {
headers: { "cache-control": "public, max-age=600" },
});
await cache.put(key, response.clone());
return response;
};
// ============================================
// PART 10: PURGE BY TAG FROM A WEBHOOK
// ============================================
curl -X POST "https://api.netlify.com/api/v1/purge" \
-H "Authorization: Bearer $NETLIFY_TOKEN" \
-H "Content-Type: application/json" \
-d '{"site_id":"abc","cache_tags":["product-42"]}'
The ten parts moved from the default the platform applies, through browser-only and split-window rules, into stale-while-revalidate, key narrowing and widening, tagging, function-level caching, manual Cache API control, and finally a targeted purge.
Quick Reference
The Two Headers
| Header | Consumed by | Stripped before client |
|---|---|---|
Cache-Control | Browser and edge | No |
Netlify-CDN-Cache-Control | Edge only | Yes |
Netlify-Vary | Edge only | Yes |
Netlify-Cache-Tag | Edge only | Yes |
Directives
| Directive | Effect |
|---|---|
max-age=N | Fresh for N seconds |
s-maxage=N | Shared-cache override of max-age |
stale-while-revalidate=N | Serve stale, refresh in background |
stale-if-error=N | Serve stale when revalidation fails |
private | Never stored by the edge |
no-store | Never stored anywhere |
immutable | Never revalidate while fresh |
Key Controls
| Control | Effect on key | Use when |
|---|---|---|
| Default | Path + query string | Nothing else varies |
Netlify-Vary: query=a,b | Only these params count | Tracking params fragment the cache |
Netlify-Vary: cookie=x | Cookie value joins key | Response is per-session |
private | Not cached at edge | Response is per-user |
Cache API
| Call | Returns |
|---|---|
caches.default.match(req) | Response or undefined |
caches.default.put(req, res) | undefined, stores if cacheable |
caches.default.delete(req) | boolean |
Best Practices
โ Do This:
# Keep the browser window short and the edge window long # โ
Cache-Control = "public, max-age=60, must-revalidate"
Netlify-CDN-Cache-Control = "public, max-age=86400"
# Add SWR to anything that changes but tolerates lag # โ
Netlify-CDN-Cache-Control = "public, max-age=600, stale-while-revalidate=3600"
# Use immutable only on fingerprinted filenames # โ
for = "/assets/*"
# Tag by entity and by collection # โ
Netlify-Cache-Tag = "products,product-42"
# Mark authenticated responses private # โ
Cache-Control = "private, max-age=0, must-revalidate"
โ Don’t Do This:
# A year of browser cache on a stable HTML path # โ
Cache-Control = "public, max-age=31536000" # on /index.html
# Cache a personalised response under the shared key # โ
Cache-Control = "public, max-age=600" # no Netlify-Vary
# Purge everything to fix one product # โ
-d '{"site_id":"abc","purge_everything":true}'
# Expect a browser with max-age=86400 to see a correction # โ
# (the purge cannot reach it)
# Rely on cache.put() for a response with max-age=0 # โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Deploy not visible | Long browser max-age on HTML | Short window plus must-revalidate |
| One user sees another’s page | Per-session response under shared key | private or Netlify-Vary: cookie=โฆ |
| Purge returns success, nothing changes | Tag mismatch between set and purge | Grep both for the exact tag string |
| Cache never hits | Tracking params fragmenting the key | Netlify-Vary: query=โฆ |
cache.put() stores nothing | Response lacks positive max-age | Set max-age or s-maxage |
| Body already consumed | response used after put | cache.put(key, response.clone()) |
| Unsafe content served | immutable on a stable path | Fingerprint the filename |
| Stale forever | stale-while-revalidate with a failing origin | Add stale-if-error and alert |
Real-World Examples
1. Fingerprinted Bundles, One Year
for = "/assets/*"
Cache-Control = "public, max-age=31536000, immutable"
2. Marketing Page, Split Windows
for = "/pricing"
Cache-Control = "public, max-age=60, must-revalidate"
Netlify-CDN-Cache-Control = "public, max-age=86400"
3. Blog Index With SWR
for = "/blog/*"
Netlify-CDN-Cache-Control = "public, max-age=600, stale-while-revalidate=3600"
4. Search Page With a Narrow Key
for = "/search"
Netlify-Vary = "query=color,size"
5. Account Page That Must Not Cache Publicly
for = "/account/*"
Cache-Control = "private, max-age=0, must-revalidate"
6. Cached Function Response
return new Response(body, {
headers: { "cache-control": "public, max-age=300", "netlify-cache-tag": "stats" },
});
7. Entity-Level Tag
"netlify-cache-tag": `product-${product.id}`,
8. Targeted Purge
curl -X POST https://api.netlify.com/api/v1/purge \
-d '{"site_id":"abc","cache_tags":["product-42"]}'
9. Manual Cache Read
const hit = await caches.default.match(key);
if (hit) return hit;
10. Manual Cache Write
await caches.default.put(key, response.clone());
Visual
Stale-While-Revalidate Over Time
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STALE-WHILE-REVALIDATE โ
โ โ
โ t=0 request -> rendered and stored โ
โ t=30 hit -> served from cache, no origin call โ
โ t=90 expired -> served STALE, refresh starts โ
โ t=90+ refresh -> new entry replaces the old one โ
โ โ
โ The visitor never waits for the refresh to finish. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Cache Key Composition
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ KEY = PATH + QUERY + DECLARED VARY โ
โ โ
โ default /p/1?color=red -> own entry โ
โ /p/1?utm=x -> own entry โ
โ โ
โ vary=query=color /p/1?color=red -> own entry โ
โ /p/1?utm=x -> same as above โ
โ โ
โ vary=cookie=sid /p/1 + sid=a -> own entry โ
โ /p/1 + sid=b -> separate entry โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
What a Purge Can Reach
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ PURGE BY TAG โ
โ โ
โ BROWSER CACHE <-- unreachable, waits for max-age โ
โ | โ
โ v โ
โ NETLIFY EDGE <-- evicted immediately by tag โ
โ | โ
โ v โ
โ ORIGIN / FUNCTION <-- consulted on the next miss โ
โ โ
โ Hence: short browser max-age on anything correctable. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Which Header Wins Where
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ RESPONSE CARRIES โ
โ Cache-Control: public, max-age=60 โ
โ Netlify-CDN-Cache-Control public, max-age=86400 โ
โ โ
โ BROWSER receives -> max-age=60 โ
โ EDGE applies -> max-age=86400 โ
โ CDN header is stripped before the client sees it. โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Default HTML header | public, max-age=0, must-revalidate |
| Browser control | Cache-Control |
| Edge-only control | Netlify-CDN-Cache-Control |
| Key widening | Netlify-Vary: cookie=โฆ |
| Key narrowing | Netlify-Vary: query=โฆ |
| Background refresh | stale-while-revalidate |
| Failure tolerance | stale-if-error |
| Invalidation label | Netlify-Cache-Tag |
| Purge endpoint | POST /api/v1/purge with cache_tags |
| Programmatic control | caches.default in Edge Functions |
Key takeaways:
- Two caches, two headers.
Cache-Controlreaches the browser and the edge;Netlify-CDN-Cache-Controlreaches only the edge and is stripped before the client sees the response, which is how you can cache for a day at the edge and a minute in the browser. stale-while-revalidatebuys availability as well as speed. Betweenmax-ageand the end of the stale window, one request refreshes the entry while everyone else is served the old copy instantly, and a failing origin does not take the page down.- The cache key must match the response’s dependencies. Add
Netlify-Vary: cookie=โฆwhen a response is per-session, and narrow it withquery=โฆwhen irrelevant parameters are fragmenting the cache. Getting this wrong in either direction is a real incident. - Tags make invalidation surgical. Label every entry with the collection and the entity โ
products,product-42โ so a correction evicts one entry and a catalogue change evicts the group, rather than purging the site. - A purge never reaches the browser. Whatever a visitor already holds stays until its own
max-ageexpires, so keep the browser window short on anything you may need to correct urgently. - The Cache API is the escape hatch.
caches.default.match,put, anddeletein an Edge Function give explicit control when headers cannot express the rule, subject to the same cacheability constraints โ a response without a positivemax-ageis silently not stored.
Remember: Caching on Netlify is a negotiation between three parties โ the browser you cannot reach, the edge you can, and the origin that pays for every miss. Set the browser window to the shortest value the content tolerates, set the edge window as long as correctness allows, and bridge the gap with stale-while-revalidate so expiry never becomes a wait. Tag what you cache so that fixing one thing does not cost you everything else, and remember that a purge is only ever half a solution, because the other half of the copies are sitting on other people’s machines.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!