Vary lists request headers that also change the response. The cache then adds those header values to its cache key (the value it uses to find a stored response). If you forget it, a cache may serve one client's version to another client.
By default, a cache keys stored responses by method and URL only. Examples of Vary:
Vary: Accept-Encodingkeeps the gzip and Brotli versions apart.Vary: Accept-Languagekeeps the English and French versions apart.
What goes wrong without it, in a shared cache such as a CDN:
- The CDN could send a Brotli body to a client that cannot decode Brotli.
- The CDN could send a French page to an English user.
- With CORS, you may copy the request's
OriginintoAccess-Control-Allow-Origin. Then you needVary: Origin. Without it, the browser blocks a cached response made for one origin when other origins receive it.
Do not vary on high-cardinality headers, meaning headers with very many different values, like User-Agent or Cookie. The cache splits into many tiny entries, and the hit rate collapses.
Varyadds request headers to the cache key.- Common
Varyheaders areAccept-Encoding,Accept-LanguageandOrigin. - A missing
Varyheader makes the cache serve the wrong version. - Headers with very many values, like
User-Agent, destroy the hit rate.
Read more
- Vary (MDN) (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Vary)developer.mozilla.org
- HTTP caching (MDN) (https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching)developer.mozilla.org