TOPIC SECURITY
CORS the browser's same-origin policiy enforcer
IN 10 SECONDS
Cross-Origin Resource Sharing (CORS) is a browser mechanism that controls which domains can access resources from your server. When a web app at `app.example.com` fetches data from `api.example.com`, the browser sends a `preflight` `OPTIONS` request first. The server responds with `Access-Control-Allow-Origin` headers to permit or deny the cross-origin request.
GOTCHA CORS is enforced by the browser, not the server. A malicious script with `curl` or Postman bypasses CORS entirely. CORS protects users from unintended cross-origin reads, not APIs from bad actors — use proper authentication for that.
HOW A PREFLIGHT REQUEST WORKS
01 Browser detects a cross-origin fetch — different domain, protocol, or port than the page's origin.
02 Browser sends an `OPTIONS` preflight request with `Origin: https://app.example.com` and `Access-Control-Request-Method: POST`.
03 Server responds with `Access-Control-Allow-Origin: https://app.example.com` (or `*`) and the allowed methods/headers.
04 Browser checks the response. If the origin is not allowed, the browser blocks the actual request with a CORS error.
05 Actual request if preflight passes, the browser sends the real `GET` or `POST` and exposes the response to JavaScript.
POKE IT YOURSELF
curl -H "Origin: https://evil.com" -v https://api.example.com/data — simulate a cross-origin request
curl -X OPTIONS -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: GET" -v https://api.example.com/data — trigger a preflight manually
Drill this topic →
~70 sec read