Cross-Origin Resource Sharing (CORS) is a browser security mechanism that selectively relaxes the Same-Origin Policy (SOP), allowing frontend JavaScript on one origin (domain, protocol, or port) to access resources from a different origin. When a frontend makes a non-simple request (using methods like PUT/DELETE, custom headers like Authorization, or Content-Type: application/json), the browser automatically dispatches an HTTP OPTIONS "preflight" request before sending the actual payload. The server must respond with appropriate Access-Control-Allow-* headers. Notably, CORS is enforced strictly by web browsers, which is why identical requests succeed in curl or Postman but fail in JavaScript.
Key Takeaways & Regulatory Summary
- Origin is strictly defined by three components: Protocol (http vs https), Domain (dmrs.in vs api.dmrs.in), and Port (:80 vs :443 vs :3000).
- CORS errors are browser security events; server-to-server HTTP calls (Node, Python, Go, curl) completely bypass CORS checks.
- Simple Requests (GET/HEAD/POST with text/plain, multipart/form-data, or x-www-form-urlencoded) do NOT trigger an OPTIONS preflight.
- Setting Content-Type to application/json immediately promotes a request to "Preflighted", triggering an automatic HTTP OPTIONS handshake.
- Access-Control-Allow-Origin: * cannot be used when Access-Control-Allow-Credentials: true is set; browsers reject wildcard credentials.
- Access-Control-Max-Age allows backend servers to cache successful preflight responses, drastically reducing round-trip latency.
1. Why CORS Exists: The Same-Origin Policy (SOP)
To comprehend why CORS errors occur, one must understand the threat model it prevents: Cross-Site Request Forgery (CSRF) and credential theft. The browser’s fundamental security boundary is the Same-Origin Policy (SOP), established by Netscape Navigator in 1995.
Imagine you are logged into your online bank at `bank.com`, with authentication cookies stored in your browser session. If you open a malicious tab at `evil.com`, without Same-Origin Policy, JavaScript on `evil.com` could execute `fetch("https://bank.com/api/transfer", { method: "POST", body: ... })`. The browser would automatically attach your authenticated banking cookies, allowing an attacker to drain your account silently! SOP blocks `evil.com` from reading or executing unauthorized requests against `bank.com`.
2. Simple Requests vs. Preflighted Requests
Not all cross-origin requests require an OPTIONS handshake. Under the W3C Fetch specification, a request is deemed a "Simple Request" and bypasses preflight if it meets ALL three conditions:
1. HTTP Method: Must be strictly GET, HEAD, or POST.
2. Headers: Can only contain automatic browser headers plus `Accept`, `Accept-Language`, `Content-Language`, and `Content-Type`.
3. Content-Type: If provided, must be strictly one of three legacy formats: `application/x-www-form-urlencoded`, `multipart/form-data`, or `text/plain`.
The moment you set `Content-Type: application/json` or attach a custom header like `Authorization: Bearer ...`, the browser classifies the request as potentially dangerous and automatically dispatches a preflight OPTIONS handshake.
3. The Wildcard (*) and Credentials Conflict Trap
A rampant bug in full-stack architecture is configuring `Access-Control-Allow-Origin: *` while simultaneously attempting to send authentication cookies via `fetch(url, { credentials: "include" })`.
The WHATWG specification explicitly forbids this combination to prevent cross-site identity leakage. If the server sends `Access-Control-Allow-Origin: *` alongside `Access-Control-Allow-Credentials: true`, the browser will immediately terminate the request with a fatal error: "The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'".
To support authenticated credentials safely: the backend must inspect the incoming Origin header dynamically, verify it against an internal whitelist (such as dmrs.in and staging.dmrs.in), and echo the exact matching origin back in Access-Control-Allow-Origin.
4. Debugging CORS: Why Postman Never Shows CORS Errors
Junior engineers frequently complain: "The API works perfectly in Postman and curl, why is my React/Vue frontend throwing a CORS error?".
Postman, curl, and backend servers are developer tools, not web browsers. They do NOT implement the browser Same-Origin Policy sandbox. When curl sends an HTTP request, it prints the raw server response immediately without checking permissions.
CORS is an agreement negotiated EXCLUSIVELY between a web browser and an HTTP server on behalf of untrusted frontend scripts. If a CORS error appears in your browser DevTools console, the fix is virtually ALWAYS on the backend API server (ensuring proper OPTIONS handling and headers), NOT inside frontend JavaScript.
5. Preflight Caching with Access-Control-Max-Age
Every preflight OPTIONS request introduces an entire extra network round-trip before the actual API call can proceed, adding 100 to 300 milliseconds of latency over mobile networks.
To eliminate this latency penalty, backend servers should always return the `Access-Control-Max-Age` header (e.g. `Access-Control-Max-Age: 86400`). This instructs the browser to cache the preflight permission for 24 hours. Subsequent API requests to the same endpoint skip the preflight entirely, executing instantly.
Practical Worked Example: A Web Frontend at https://dmrs.in Fetching JSON Data from an API at https://api.dmrs.in
A client-side calculator on dmrs.in sends a JSON payload with a Bearer authentication token to a microservice hosted on a subdomain api.dmrs.in.
| Communication Step | HTTP Method & Phase | Request / Response Headers Exchanged | Browser Engine Behavior |
|---|---|---|---|
| Step 1: Origin Evaluation | Browser Internal Check | Request Origin: https://dmrs.in vs Target: https://api.dmrs.in | Different subdomains detected; triggers Cross-Origin evaluation |
| Step 2: Preflight Trigger | Browser Internal Check | Headers contain "Authorization" and Content-Type: application/json | Not a simple request; browser pauses actual request and initiates Preflight |
| Step 3: Preflight Dispatch | OPTIONS /calculate | Origin: https://dmrs.in Access-Control-Request-Method: POST Access-Control-Request-Headers: authorization, content-type | Zero body payload sent; query server capability first |
| Step 4: Server Preflight Response | HTTP/1.1 204 No Content | Access-Control-Allow-Origin: https://dmrs.in Access-Control-Allow-Methods: POST, OPTIONS Access-Control-Allow-Headers: Authorization, Content-Type Access-Control-Max-Age: 86400 | Server explicitly permits the origin and headers; caches decision for 24 hours |
| Step 5: Actual Payload Dispatch | POST /calculate | Origin: https://dmrs.in Authorization: Bearer xyz... Content-Type: application/json Payload: {"principal": 5000000} | Browser releases held request; transmits actual JSON payload |
| Step 6: Final Response Delivered | HTTP/1.1 200 OK | Access-Control-Allow-Origin: https://dmrs.in Body: {"emi": 43391} | Browser permits JavaScript to read response data into DOM |
Core HTTP Response Headers in the CORS Protocol
Statutory headers defined in the W3C / WHATWG Fetch Standard governing cross-origin permissions.
| Response Header Name | Expected Syntax / Value | Functional Security Role |
|---|---|---|
| Access-Control-Allow-Origin | https://dmrs.in (or wildcard "*") | Declares which origin domain is permitted to read response data |
| Access-Control-Allow-Methods | GET, POST, PUT, DELETE, OPTIONS | Comma-separated whitelist of permitted HTTP request verbs |
| Access-Control-Allow-Headers | Content-Type, Authorization, X-Requested-With | Whitelist of custom HTTP headers the client is permitted to transmit |
| Access-Control-Allow-Credentials | "true" (boolean string) | Informs browser whether cookies, TLS client certs, or auth headers can be exposed |
| Access-Control-Max-Age | Integer (e.g. 86400 seconds = 24 hours) | Instructs browser to cache preflight OPTIONS response, avoiding round-trips on future calls |
| Access-Control-Expose-Headers | X-RateLimit-Remaining, Content-Length | Whitelist of custom response headers client JavaScript is allowed to inspect |
Mistakes I See Most Often from Practice
- Attempting to "Fix" CORS by Setting Request Headers: Adding headers like "Access-Control-Allow-Origin" in frontend fetch() calls is useless; CORS response headers must be emitted by the receiving server.
- Disabling Browser Web Security Flags in Development: Using Chrome flags like --disable-web-security hides CORS bugs locally that will inevitably break in production.
- Responding with HTTP 403 or 401 on OPTIONS Requests: Preflight OPTIONS requests do not carry authentication cookies. Rejecting unauthenticated OPTIONS calls breaks the entire handshake; always return HTTP 204 to valid preflight origins.
- Ignoring the Access-Control-Max-Age Header: Failing to set Max-Age forces the browser to re-execute an OPTIONS preflight before every single API call, halving mobile performance.
Official Statutory & Technical References
Verify rules directly with primary statutory sources:
W3C / WHATWG Fetch Living Standard (CORS Protocol)
Authoritative specification governing preflight handshakes and origin access control.
Mozilla Developer Network (MDN): Cross-Origin Resource Sharing
Comprehensive web architecture documentation on simple requests, preflights, and security headers.