serve
serve copied to clipboard
Support avoiding the wildcard in CORS headers
Followon to https://github.com/vercel/serve/issues/319
Serve sends CORS headers, however the Access-Control-Allow-Origin header is * which is problematic because in certain requests, the browser blocks the * wildcard because of security or something. So you have to mirror the Origin header back, instead of sending *.
A sample browser error:
Failed to load http://localhost:3010/appentries.json: The value of the 'Access-Control-Allow-Origin' header
in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
Origin 'http://localhost:4000' is therefore not allowed access. The credentials mode of requests initiated
by the XMLHttpRequest is controlled by the withCredentials attribute.
You can create a serve.json file to send the right headers:
{
"headers": [
{
"source": "**/*",
"headers": [
{
"key": "Access-Control-Allow-Origin",
"value": "http://localhost:8088"
},
{
"key": "Access-Control-Allow-Credentials",
"value": "true"
}
]
}
]
}
However this is not ideal because 1) it's not dynamic; you have to hard-code the origin, and there can only be one origin, and 2) it's not as convenient as npx serve; you have to create a file.
It would be nice to have a flag for this, like --cors-mirror-origin. Would a PR for that be welcome?
shameless self-promotion alert:
this feature is available in my @warren-bank/serve fork of serve
notes:
- when the
--corscli option is enabled:- when a request includes an
originheader:- the cors response header echoes this origin
- credentials are allowed
- when no
originheader is present:- wildcards are used
- credentials are not allowed
- when a request includes an
http-server also has the issue https://github.com/http-party/http-server/issues/729
live-server got it right.
npx serve --cors does not work correctly against latest Chrome 100.0.4896.75, but npx live-server --cors works nicely.
Seems like this is still an issue if I'm not mistaken? Trying to find a solution to this. We actually have a security audit complaining about the * allow origin header in our frontend app served from Vercel.
I'm aware a specific origin can be set in vercel.json now but as far as I'm aware that remains only a hardcoded option and won't even accept regex etc. to match a set of origins?