What is CORS, and why does it keep blocking your requests?
CORS errors are a rite of passage for web developers. They are confusing because the request often works in a tool like curl but fails in the browser. That's the clue: CORS is enforced by browsers.
The background: same-origin policy Browsers restrict scripts on one origin (scheme + domain + port) from reading responses from another origin. This prevents a malicious site from reading your data on other sites using your logged-in cookies.
CORS (Cross-Origin Resource Sharing) is how a server opts in to allowing specific other origins to read its responses.
How it works:
- For simple requests, the browser sends the request with an
Originheader. If the response includes a matchingAccess-Control-Allow-Origin, the script can read it. - For other requests (custom headers, JSON content type, methods like PUT or DELETE), the browser first sends a preflight
OPTIONSrequest asking permission. - Credentials (cookies) require
Access-Control-Allow-Credentials: trueand a specific origin, not a wildcard.
Common fixes:
- Configure CORS on the server you're calling, listing your front-end origin.
- Make sure the server responds correctly to
OPTIONSpreflights, including for error routes. - In development, use your dev server's proxy so requests appear same-origin.
Don't: set Access-Control-Allow-Origin: * with credentials, or disable CORS in your browser as a "fix."
What's the most confusing CORS issue you've hit? Do you prefer configuring CORS or avoiding it with a same-origin proxy?
Comments · 4
The part that confused me for ages: CORS is enforced by the browser, not the server. That's why curl works but the page doesn't.
Please don't "fix" it with a wildcard origin in production just because it makes the error go away. Allow the exact origins you need.
Why does the browser send an OPTIONS request first? I see it in the network tab and never know why.
It's a "preflight" check. For certain requests the browser asks the server first whether the real request is allowed. Your server needs to answer OPTIONS with the right headers.