What is CORS (Cross-Origin Resource Sharing), and what problem — created by the Same-Origin Policy — does it solve?
A set of response headers a server uses to deliberately relax the Same-Origin Policy — telling the browser "these specific other origins are allowed to read my responses."
* The server's Access-Control-Allow-Origin decides whether the browser lets the calling script read the response. *
The Same-Origin Policy is a blunt default: a script on origin A may not read any response from origin B. Safe, but it breaks a legitimate need — a single-page app on app.example.com calling its own API on api.example.com, or any public API meant to be consumed cross-origin. CORS is the controlled exception, and crucially the server decides who gets it.
How it works:
- The browser attaches an
Origin:header to the cross-origin request. - The server replies with
Access-Control-Allow-Origin:naming the origin it trusts (or*for "anyone"). Only then does the browser hand the response body to the calling script — otherwise it fetches the response but blocks the script from reading it. - For requests beyond a "simple" GET/POST (custom headers,
PUT/DELETE), the browser first sends a preflightOPTIONSrequest and checksAccess-Control-Allow-Methods/-Headersbefore sending the real one.
The classic misconfiguration: Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true — letting any site read authenticated responses, reintroducing exactly the cross-origin data theft SOP was meant to prevent. Browsers forbid literal * with credentials, so the real-world bug is a server that reflects the request's Origin back without an allowlist — same hole, dressed up.
Tip: CORS does not protect your server — it only tells the browser who may read a response. It is not a CSRF defense and not a substitute for authentication: a non-browser client (curl, a script) ignores it entirely.
Go deeper:
Cross-Origin Resource Sharing (CORS) — MDN — simple vs preflighted requests and every
Access-Control-*header.Cross-origin resource sharing — Wikipedia — the mechanism and its security considerations.