CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls how web pages in one origin (domain, protocol, port combination) can request resources from a different origin. It extends the Same-Origin Policy (SOP) to allow controlled cross-origin access.
The Same-Origin Policy
By default, browsers block JavaScript on https://app.com from making AJAX requests to https://api.other.com. This prevents malicious websites from making requests to other services using the user's credentials. CORS is the mechanism that allows servers to selectively relax this restriction.
How CORS Works
- The browser sends an HTTP request with an
Originheader. - The server responds with CORS headers indicating whether the origin is allowed.
- If allowed, the browser lets the page access the response. If not, the browser blocks it.
CORS Response Headers
Access-Control-Allow-Origin: https://app.com— Allows a specific origin.Access-Control-Allow-Origin: *— Allows any origin (unsafe for authenticated APIs).Access-Control-Allow-Methods: GET, POST, PUT— Allowed HTTP methods.Access-Control-Allow-Headers: Content-Type, Authorization— Allowed request headers.Access-Control-Allow-Credentials: true— Allows cookies to be sent cross-origin.
Preflight Requests
For non-simple requests (DELETE, PUT, custom headers), browsers send an OPTIONS preflight request first to check if the server allows the actual request. Only if the preflight succeeds does the browser send the real request.
Common Mistakes
- Using
*withAllow-Credentials: true— browsers reject this combination. - Reflecting the
Originheader blindly without validation — creates security vulnerabilities.