HTTP Caching Strategies for Web Developers
HTTP Caching Strategies for Web Developers
Effective caching is the single biggest performance improvement you can make. A cached response has zero latency and zero server load.
Cache-Control Header
The primary caching directive:
Cache-Control: public, max-age=31536000, immutable
Directives
| Directive | Meaning |
|-----------|---------|
| public | Any cache can store |
| private | Only browser can store |
| no-cache | Must revalidate before using |
| no-store | Don't cache at all |
| max-age=N | Fresh for N seconds |
| s-maxage=N | CDN-specific max-age |
| immutable | Won't change; skip revalidation |
| stale-while-revalidate=N | Serve stale while fetching fresh |
Caching Strategies by Resource Type
Static Assets (CSS, JS, images, fonts)
Cache-Control: public, max-age=31536000, immutable
Use content-hashed filenames (main.abc123.js). Cache forever. When the content changes, the filename changes, busting the cache automatically.
HTML Pages
Cache-Control: no-cache
Always revalidate. The HTML references hashed asset URLs, so it must always be fresh to point to the latest versions.
API Responses
Cache-Control: private, max-age=60, stale-while-revalidate=300
Cache for 60 seconds, serve stale for up to 5 minutes while revalidating in the background.
Sensitive Data
Cache-Control: no-store
Never cache. Used for authenticated API responses with sensitive data.
ETag and Conditional Requests
ETags enable efficient revalidation:
ETag: "abc123"If-None-Match: "abc123"CDN Caching
CDNs (Cloudflare, Vercel, AWS CloudFront) add a caching layer between your server and users:
s-maxage to control CDN cache duration independentlySurrogate-Key or Cache-Tag headers for targeted purgingVary header to cache different versions per Accept-Encoding, Accept-Language, etc.Common Mistakes
Caching HTML with long max-age — users get stale pages with broken asset references. Not hashing filenames — changing CSS without changing the filename means users see the old version. Forgetting Vary — if you serve different content for mobile vs desktop, addVary: User-Agent.
no-cache vs no-store — no-cache allows caching but requires revalidation. no-store prevents caching entirely.
Conclusion
Hash your static assets and cache them forever. Always revalidate HTML. Use stale-while-revalidate for API responses. CDN caching multiplies these benefits globally.