gotchahttpMajorpending
Gotcha: HTTP caching headers interact in complex ways
Viewed 0 times
Cache-ControlETagno-cacheno-storemax-ageimmutable
Error Messages
Problem
Setting cache headers incorrectly causes stale data, unnecessary revalidation, or no caching at all. Cache-Control, ETag, and Expires interact in confusing ways.
Solution
HTTP caching decision tree:
Cache-Control: no-store
(Use for: sensitive data, real-time prices)
Cache-Control: no-cache
ETag: "abc123"
(Client checks with If-None-Match, gets 304 if unchanged)
Cache-Control: public, max-age=3600 (1 hour)
(Use for: static assets, API responses that rarely change)
Cache-Control: public, max-age=31536000, immutable
(Use for: app.a1b2c3.js, style.d4e5f6.css)
Common mistakes:
// Express.js:
app.use('/static', express.static('public', {
maxAge: '1y',
immutable: true, // For fingerprinted files
}));
app.get('/api/data', (req, res) => {
res.set('Cache-Control', 'private, max-age=60');
res.json(data);
});
- Don't cache at all:
Cache-Control: no-store
(Use for: sensitive data, real-time prices)
- Cache but revalidate every time:
Cache-Control: no-cache
ETag: "abc123"
(Client checks with If-None-Match, gets 304 if unchanged)
- Cache for a duration:
Cache-Control: public, max-age=3600 (1 hour)
(Use for: static assets, API responses that rarely change)
- Immutable assets (fingerprinted filenames):
Cache-Control: public, max-age=31536000, immutable
(Use for: app.a1b2c3.js, style.d4e5f6.css)
Common mistakes:
- no-cache does NOT mean "don't cache" — it means "revalidate"
- no-store means "don't cache" (what you probably want)
- max-age=0 + must-revalidate = same as no-cache
- Expires header is ignored if Cache-Control is present
- CDNs may cache even with private (use s-maxage for CDN)
// Express.js:
app.use('/static', express.static('public', {
maxAge: '1y',
immutable: true, // For fingerprinted files
}));
app.get('/api/data', (req, res) => {
res.set('Cache-Control', 'private, max-age=60');
res.json(data);
});
Why
HTTP caching is the most impactful performance optimization for web apps. Misconfigured headers either waste bandwidth or serve stale data.
Revisions (0)
No revisions yet.