पाठ 16 / 32
HTTP Caching at the CDN
यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।
Control CDN and browser caching with Cache-Control directives and choose cache keys that never mix users' data.
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर
Caching is the cheapest edge compute
Before writing edge code, ask whether the response can simply be cached at the CDN. The Cache-Control response header drives this. max-age=N says how many seconds a response stays fresh for any cache, including the browser. s-maxage=N overrides that for shared caches such as CDNs only. stale-while-revalidate=N lets a cache serve a slightly stale copy while it fetches a fresh one in the background, hiding origin latency. private forbids shared caches from storing the response, which is what you want for anything user-specific, and no-store forbids storing it anywhere. The cache key, normally the URL plus selected headers, decides which requests share a cached copy, and Vary adds request headers to it. A common pattern is short browser caching, longer CDN caching and an explicit purge when content changes, so most requests never reach your function at all.
Setting cache headers from an edge function
Browsers always revalidate (max-age=0), the CDN keeps the response fresh for 60 seconds, and for up to five minutes after that it may serve the stale copy while refreshing.
// Cache a product API response at the CDN for 60 s; serve stale up to 5 min while refreshing.
const worker = {
async fetch(request) {
const body = JSON.stringify({ sku: 'kurta-42', priceInr: 1299 });
return new Response(body, {
headers: {
'content-type': 'application/json',
// browsers: always revalidate; shared caches (CDN): 60 s fresh
'cache-control': 'public, max-age=0, s-maxage=60, stale-while-revalidate=300',
'vary': 'accept-encoding',
},
});
},
};
const res = await worker.fetch(new Request('https://api.example/products/kurta-42'));
console.log(res.headers.get('cache-control'));
Output:
public, max-age=0, s-maxage=60, stale-while-revalidate=300
Layers between a user and the origin
A request is answered by the first layer that can: the edge cache, then edge data such as a KV store, and only then the origin.
Never cache one user's page for everyone
A response that contains a user's name, cart or token must not be stored by a shared cache. Mark it private (or no-store), and be careful with responses that set cookies. Caching a logged-in page publicly is a real and embarrassing data leak.
त्वरित जाँच: Which directive sets freshness for shared caches like a CDN without changing what browsers do?
- private
- no-store
- s-maxage
- must-revalidate
Answer
s-maxage — `s-maxage` applies only to shared caches. `private` and `no-store` prevent caching rather than tune it.