Skip to main content

πŸ—‚οΈ HTTP Cache Control

  1. The HTTP cache-control header contains some directives in both requests and responses that control caching in browsers and shared caches (CDNs, proxies).
  2. We can only modify CORS-safelisted response header with cache-control directives, as Forbidden-request header cannot be updated programmatically (the user agent updates this).

Cache-Control Directives in Requests vs. Responses​

DirectiveRequest (C β†’ S)Response (S β†’ C)Description & Use Case
no-cacheβœ… Yesβœ… YesForces revalidation before serving cached content. Used when the client wants fresh data.
no-storeβœ… Yesβœ… YesPrevents caching entirely. Used for sensitive data like authentication, banking pages.
max-age=<seconds>βœ… Yesβœ… YesSpecifies how long content can be considered fresh. Used to control caching behavior.
s-maxage=<seconds>❌ Noβœ… YesSimilar to max-age, but applies to shared caches (CDNs, proxies).
public❌ Noβœ… YesAllows caching by any cache (browser, proxies, CDNs). Used for static assets.
private❌ Noβœ… YesRestricts caching to the end-user’s browser only. Used for user-specific data.
must-revalidate❌ Noβœ… YesForces caches to revalidate content before serving stale responses. Used along with max-age
proxy-revalidate❌ Noβœ… YesForces shared caches (CDNs, proxies) to revalidate stale content.
no-transform❌ Noβœ… YesPrevents caches from modifying content (e.g., image compression by proxies).
stale-while-revalidate=<seconds>❌ Noβœ… YesAllows serving stale content while revalidating in the background.
stale-if-error=<seconds>❌ Noβœ… YesServes stale content when the origin server is down.
immutable❌ Noβœ… YesIndicates that a resource will not change while cached. Used for versioned assets.

Note​

immutable and stale-while-revalidate do not have full browser support.

Commonly Used Patterns​

Cache Static Assets​

Cache-Control: public, immutable, max-age=432432434
  1. Used for versioned assets (e.g., logo-v1.png, app-v2.js)
  2. public: Allows caching for all (CDN, browser, proxies)
  3. immutable: No need to revalidate by browser

Prevent Caching Entirely​

Cache-Control: no-store

Use case: Login pages, transaction pages

Ensure Fresh Data Always​

Cache-Control: no-cache, must-revalidate

Use case: Dashboard analytics

Serve Cached Content if Server Failure​

Cache-Control: public, max-age=600, stale-if-error=3600

Use case: For good user experience

Optimize Content Delivery on CDN​

Cache-Control: public, max-age=600, s-maxage=86400

CDN caches content for 1 day and browser for 10 minutes.