The Vary response header tells caching proxies (such as CDNs, reverse proxies, and browsers) which request headers were used by the origin server to select the response representation.
Why the Vary header is critical
By default, an HTTP cache indexes responses using the request method and URL as the cache key (GET /api/data).
If an API returns different content depending on headers (such as compression via Accept-Encoding or dynamic CORS headers via Origin), failing to set Vary will cause the cache to serve the wrong representation to other clients:
- Without
Vary: Accept-Encoding: A client requesting uncompressed data might receive a cached Gzip-compressed binary blob, resulting in garbled text. - Without
Vary: Origin: A CDN might cacheAccess-Control-Allow-Origin: https://app1.testand serve it tohttps://app2.test, breaking CORS.
Common Vary header values
Vary: Accept-Encoding
Vary: Accept-Encoding, Origin
Vary: Accept, Accept-Language
Caching danger: Vary: *
Setting Vary: * instructs caches that each request must be treated as uniquely uncacheable, completely disabling shared caching across CDNs.
How to verify with curl
Inspect the Vary header on an API response:
curl -i https://api.example.test/v1/assets/app.js \
-H "Accept-Encoding: gzip, br"
Key takeaway
The Vary header prevents cache corruption by instructing CDNs and proxies to include specified request headers in the secondary cache key. Always include Vary: Accept-Encoding for compressible assets and Vary: Origin for dynamic CORS endpoints.