Repository navigation
Description
The Vary HTTP response header is useful to ensure proper caching of CORS responses and prevent cache poisoning. However, it comes with a downside: (potentially significantly) increasing the cache size, since each client's origin will create a different cached value.
The standard mentions:
If
Access-Control-Allow-Originis set to * or a static origin for a particular resource, then configure the server to always sendAccess-Control-Allow-Originin responses for the resource — for non-CORS requests as well as CORS requests — and do not useVary.
In other words, if the CORS response is always the same regardless of the Origin request header, Vary: Origin should not be set. Currently, this module mostly gets it right except in two cases:
- If the
originoption is a function, regardless of the return value of that function (including'*'),Vary: Originshould be set, since that function might (and most likely did) use theOriginrequest header.
Lines 209 to 216 in 53312a5
| var originCallback = null; | |
| if (corsOptions.origin && typeof corsOptions.origin === 'function') { | |
| originCallback = corsOptions.origin; | |
| } else if (corsOptions.origin) { | |
| originCallback = function (origin, cb) { | |
| cb(null, corsOptions.origin); | |
| }; | |
| } |
Lines 41 to 46 in 53312a5
| if (!options.origin || options.origin === '*') { | |
| // allow any origin | |
| headers.push([{ | |
| key: 'Access-Control-Allow-Origin', | |
| value: '*' | |
| }]); |
- If the
originoption is a string,Vary: Originshould not be set, sinceAccess-Control-Allow-Originis always the same value, and theOriginrequest header is ignored.
Lines 47 to 56 in 53312a5
| } else if (isString(options.origin)) { | |
| // fixed origin | |
| headers.push([{ | |
| key: 'Access-Control-Allow-Origin', | |
| value: options.origin | |
| }]); | |
| headers.push([{ | |
| key: 'Vary', | |
| value: 'Origin' | |
| }]); |
Activity
jub0bs commentedon Feb 17, 2025
Relevant: https://jub0bs.com/posts/2023-02-08-fearless-cors/#do-not-support-custom-callbacks
fix: do not set Vary: Origin for static string origin option