patternjavascriptModerate
Vary Header Tells Caches Which Request Headers Affect the Response
Viewed 0 times
vary headercache keycontent negotiationaccept-encodingaccept-languagecdn
Problem
A CDN serves a compressed (gzip) response to a client that doesn't support compression, causing garbled output, because it cached without accounting for Accept-Encoding.
Solution
Set
Vary to list every request header that affects the response content. The cache uses these headers as secondary keys.// Vary on encoding and language
res.setHeader('Vary', 'Accept-Encoding, Accept-Language');
// For authenticated endpoints Vary on Authorization
// (but prefer Cache-Control: private instead)
res.setHeader('Vary', 'Accept-Encoding, Cookie');Why
Without Vary, a cache treats all requests to the same URL as interchangeable. Vary adds dimensions to the cache key, ensuring clients get the response variant appropriate for their capabilities.
Gotchas
Vary: *means every response is unique and must not be cached — effectively disables caching.- Varying on Cookie or Authorization causes cache misses for every user. Prefer Cache-Control: private.
- Some CDNs (Cloudflare) ignore Vary on Cookie entirely; read your CDN's docs.
Revisions (0)
No revisions yet.