ποΈ HTTP Cache Control
- The HTTP
cache-controlheader contains some directives in both requests and responses that control caching in browsers and shared caches (CDNs, proxies). - We can only modify
CORS-safelisted response headerwith cache-control directives, asForbidden-request headercannot be updated programmatically (the user agent updates this).
Cache-Control Directives in Requests vs. Responsesβ
| Directive | Request (C β S) | Response (S β C) | Description & Use Case |
|---|---|---|---|
no-cache | β Yes | β Yes | Forces revalidation before serving cached content. Used when the client wants fresh data. |
no-store | β Yes | β Yes | Prevents caching entirely. Used for sensitive data like authentication, banking pages. |
max-age=<seconds> | β Yes | β Yes | Specifies how long content can be considered fresh. Used to control caching behavior. |
s-maxage=<seconds> | β No | β Yes | Similar to max-age, but applies to shared caches (CDNs, proxies). |
public | β No | β Yes | Allows caching by any cache (browser, proxies, CDNs). Used for static assets. |
private | β No | β Yes | Restricts caching to the end-userβs browser only. Used for user-specific data. |
must-revalidate | β No | β Yes | Forces caches to revalidate content before serving stale responses. Used along with max-age |
proxy-revalidate | β No | β Yes | Forces shared caches (CDNs, proxies) to revalidate stale content. |
no-transform | β No | β Yes | Prevents caches from modifying content (e.g., image compression by proxies). |
stale-while-revalidate=<seconds> | β No | β Yes | Allows serving stale content while revalidating in the background. |
stale-if-error=<seconds> | β No | β Yes | Serves stale content when the origin server is down. |
immutable | β No | β Yes | Indicates 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
- Used for versioned assets (e.g., logo-v1.png, app-v2.js)
public: Allows caching for all (CDN, browser, proxies)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.