snippethttpMajorpending
HTTP Caching Headers Explained - Cache-Control, ETag, and Vary
Viewed 0 times
Cache-ControlETagVaryHTTP cachingmax-ageimmutableno-cache vs no-store
Problem
Incorrectly configured HTTP cache headers cause either stale content being served or unnecessary re-downloads, wasting bandwidth and degrading UX.
Solution
HTTP caching header guide:
Common patterns:
# Static assets (CSS, JS, images) - cache forever, bust with filename hash
Cache-Control: public, max-age=31536000, immutable
# URL: /static/app.a1b2c3.js (hash changes on update)
# HTML pages - always revalidate
Cache-Control: no-cache
# no-cache means 'cache but revalidate every time' (NOT 'don't cache')
# Sensitive data - never cache
Cache-Control: no-store
# Truly prevents caching (use for auth tokens, personal data)
# API responses - cache briefly
Cache-Control: private, max-age=60
# private = only browser cache, not CDN/proxy
# ETag for conditional requests
ETag: "abc123"
# Client sends: If-None-Match: "abc123"
# Server responds: 304 Not Modified (no body) or 200 with new data
# Vary - cache different versions
Vary: Accept-Encoding, Accept-Language
# Separate cache entries for gzip vs br, en vs frCommon patterns:
# Nginx configuration
location /static/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
location /api/ {
add_header Cache-Control "private, no-cache";
add_header Vary "Authorization";
}
location / {
add_header Cache-Control "no-cache";
etag on;
}// Express.js
app.use('/static', express.static('public', {
maxAge: '1y',
immutable: true
}));Why
Proper HTTP caching can reduce server load by 80%+ and make pages load instantly from cache. But wrong headers cause users to see stale content or force unnecessary downloads.
Gotchas
- no-cache != no caching. no-cache = 'revalidate before use'. no-store = 'truly don't cache'
- Vary: * effectively disables caching - be specific with Vary headers
Context
Configuring HTTP caching for web applications
Revisions (0)
No revisions yet.