Caching Headers Explained: s-maxage, SWR, and immutable
Use Cache-Control: public, s-maxage=3600, stale-while-revalidate=86400 on HTML so a CDN serves cached pages instantly and refreshes them in the background, and public, max-age=31536000, immutable on hashed static assets so they are cached forever.
Cache-Control is a small language for telling caches exactly how long they may serve a response and what to do when it goes stale. Getting it right is most of a fast site.
s-maxage vs max-age
max-age controls the browser cache; s-maxage controls shared caches like a CDN. On HTML you typically want a modest s-maxage so the CDN serves cached copies while your origin stays idle.
stale-while-revalidate
SWR lets a cache serve a slightly stale response instantly while it revalidates in the background. Users never wait for a refresh; they just occasionally get content that is a few seconds old.
immutable for hashed assets
When a filename contains a content hash, its contents can never change. Mark it public, max-age=31536000, immutable and browsers will never revalidate it — the fastest possible load.
Match headers to your revalidation strategy
Caching headers and on-demand revalidation work together: long CDN TTLs are safe precisely because a publish event can purge exactly the affected pages.
Frequently asked questions
- What does stale-while-revalidate do?
- It lets a cache serve a stale response immediately while fetching a fresh one in the background, so users get an instant response and the cache updates without blocking anyone.