CORS: what it protects, and what it doesn't
The same-origin policy stops other websites from reading your API's responses in a user's browser. CORS headers relax that rule. A short guide to what CORS actually does, the one misconfiguration that turns it into a data leak, and what it's not.
In one sentence
CORS decides which other websites can read your responses from a user's browser. Never reflect any Origin with Allow-Credentials: true, and remember CORS is not authentication.
Who can read the response?
By default, JavaScript on evil.example can send a request to your API, but the browser won't let it read the response. CORS headers are your API telling the browser "this other origin is allowed to read it".
GET https://api.shop.test/me Origin: https://evil.example Cookie: session=8f3a…Response headers
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://evil.example
Access-Control-Allow-Credentials: true
{ "email": "ana@mail.test", "address": "…" }Yes
⚠ evil.example reads the logged-in user's private data
CORS only controls what other sites can READ. It doesn't stop the request from being sent (that's CSRF's job), and it's not an access control for your API.
Rules of thumb
- Public data, no cookies:
Access-Control-Allow-Origin: *is fine. - Cookie-authenticated APIs: an explicit allowlist of your own origins plus
Allow-Credentials: true. Compare exact strings;endsWith("shop.test")also matchesevilshop.test. - Never reflect the request's Origin header blindly, and don't allow
null(sandboxed iframes and local files send it). - CORS doesn't stop requests: a cross-site POST still reaches your server, so state-changing endpoints still need CSRF protection.
- CORS doesn't protect from non-browsers: curl and servers ignore it. Your API still needs real authentication and authorization.
Key takeaways
- 01CORS controls cross-origin reads in browsers, nothing more.
- 02Use an exact allowlist when credentials are involved.
- 03Reflecting any Origin with credentials leaks user data to any site.
- 04Keep CSRF protection and real authorization regardless of CORS.
Check your understanding
1 of 3
What does CORS control?
Related concepts
CSRF
Cookies prove which browser sent a request, not which site asked for it. SameSite cookies and CSRF tokens tell your server the request really came from your own pages.
6 min read →Sessions & cookies
A session cookie is as good as a password while it's valid. Ship it as HttpOnly; Secure; SameSite=Lax, keep it short-lived, and rotate it on login and privilege changes.
7 min read →API data exposure
Decide on the server which fields each audience may see and change, return only those, and authorize every object and every property.
6 min read →