Skip to content

fix: always set Vary: Origin in CORS middleware - #429

Open
ilovesugarr wants to merge 1 commit into
expressjs:masterfrom
ilovesugarr:fix/always-set-vary-origin
Open

ilovesugarr wants to merge 1 commit into
expressjs:masterfrom
ilovesugarr:fix/always-set-vary-origin

Conversation

@ilovesugarr

Copy link
Copy Markdown

Summary

Ensure the Vary: Origin response header is set on all responses processed by the CORS middleware, including requests where the Origin header is absent.

Motivation

Without Vary: Origin, caching proxies or CDNs may cache a non-CORS response for requests without an Origin header and serve it to subsequent cross-origin requests, causing incorrect CORS behavior. Closes #330.

Implementation

Invoke vary(res, 'Origin') unconditionally at the start of the cors middleware function in lib/index.js.

Testing

Added a unit test in test/test.js asserting that Vary: Origin is set even when the request does not include an Origin header.

@ilovesugarr ilovesugarr changed the title fix: always set Vary: Origin in CORS middleware (#330) fix: always set Vary: Origin in CORS middleware (#429) Aug 1, 2026
@ilovesugarr ilovesugarr changed the title fix: always set Vary: Origin in CORS middleware (#429) fix: always set Vary: Origin in CORS middleware Aug 1, 2026

@kilisamemarisaaa kilisamemarisaaa left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I found a caching regression introduced by the unconditional vary(res, 'Origin') call in 8c960b5969c8bfe090ec1c53391874f0520dcf9c.

I ran the exact PR source locally with a GET request that has no Origin header. cors() now returns Access-Control-Allow-Origin: * plus Vary: Origin; the current master returns Access-Control-Allow-Origin: * without Vary. With the default origin: '*', the response is identical for every request and does not vary on Origin, so adding Vary needlessly partitions cache entries by arbitrary origins (and conflicts with the Fetch guidance referenced in #332). The same extra header is also produced for an explicit static origin.

Could this be limited to configurations whose CORS response actually depends on the request origin (for example true, a regexp/array, or a callback), with regression tests for default cors() and static-origin configurations? The no-Origin dynamic-origin case should still retain Vary: Origin, which is the useful part of this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Vary: Origin should be set on non-CORS request

2 participants