Understanding Cross-Origin Resource Sharing (CORS)
Cross-Origin Resource Sharing (CORS) is a browser security mechanism enforced by the Same-Origin Policy (SOP). When a web application running on https://app.example.com requests data from an API hosted on https://api.example.com, the browser automatically blocks the response unless the API explicitly responds with matching Access-Control-Allow-* HTTP headers.
How the Browser Preflight (OPTIONS) Check Works
For non-simple requests (requests using methods other than GET/POST/HEAD, or containing custom headers like Authorization), modern browsers initiate an automatic HTTP OPTIONS preflight request before sending the actual payload. If the server does not return an authorized Access-Control-Allow-Origin matching the client's Origin, the browser halts execution and raises a CORS console error.
Common CORS Security Gotchas
- Wildcard + Credentials Incompatibility: Setting
Access-Control-Allow-Origin: *alongsideAccess-Control-Allow-Credentials: trueis forbidden by the W3C spec. If sending cookies or Authorization headers, you must reflect or whitelist explicit origin domains. - Access-Control-Max-Age: Setting a healthy preflight cache TTL (such as
86400seconds / 24 hours) drastically speeds up SPA performance by eliminating redundant preflight network requests. - Exposed Headers: Custom headers returned by your backend (like
X-Total-CountorContent-Range) are invisible to client-side JavaScript unless declared inAccess-Control-Expose-Headers.