CORS is a browser read permission, not a gate in front of your API. How simple and preflighted requests differ, why credentials kill the wildcard, and the Origin-reflection bug that leaks user data.
CORS does not protect your server. It is a browser rule that decides whether JavaScript on one origin may read a response from another, and almost every confusing CORS bug comes from treating it as an access-control layer for the API itself.
That framing explains the things that look like contradictions: why curl works when the browser fails, why a blocked POST still changed data in your database, and why the console says "No 'Access-Control-Allow-Origin' header" when the real problem is a 500 from your auth middleware.
An origin is the triple of scheme, host and port. https://app.example.com and https://api.example.com are different origins; so are http://localhost:3000 and http://localhost:8080. Under the same-origin policy, a page can send plenty of cross-origin requests (forms, images, scripts have done this since the 1990s), but script on that page cannot read the responses.
CORS, defined today in the WHATWG Fetch standard, is the opt-in that lets a server say "this other origin may read what I return." Every part of it is enforced by the browser. The server only emits headers; the browser decides what to do with them. Nothing stops a script, a backend service or an attacker with curl from calling your API directly, because none of them run the CORS check at all.
The Fetch spec splits cross-origin requests into two kinds, and the split is where most surprises live.
A request is "simple" (the spec calls it a request that needs no preflight) when it uses GET, HEAD or POST, sets only CORS-safelisted headers such as Accept, Accept-Language and Content-Language, and, if it sets Content-Type, uses one of application/x-www-form-urlencoded, multipart/form-data or text/plain.
These are exactly the requests an HTML form could already send, so the browser sends them straight away with an Origin header. The server processes the request in full. Only when the response comes back does the browser check Access-Control-Allow-Origin and decide whether your script gets to see it.
That ordering is the root of the most dangerous misunderstanding: a CORS failure on a simple request does not mean the request didn't run. A POST with a text/plain body to /api/transfer executes, writes to the database, and only then gets hidden from the calling script. CORS is not CSRF protection.
Use PUT, PATCH or DELETE, send Content-Type: application/json, or add any custom header (an Authorization bearer token, X-Request-Id, Idempotency-Key) and the browser first sends an OPTIONS request asking permission:
The preflight carries no cookies and no Authorization header, by design. If the answer approves the method, headers and origin, the browser sends the real request; if not, the real request never leaves the browser. So for non-simple requests, CORS genuinely does stop the side effect. That asymmetry between the two request kinds is the whole game.
| Header | Sent on | What it controls | Common mistake |
|---|---|---|---|
Access-Control-Allow-Origin | preflight and actual response | Which single origin (or *) may read the response | Listing several origins in one value; only one is allowed |
Access-Control-Allow-Methods | preflight | Methods allowed for the real request | Forgetting PATCH or DELETE |
Access-Control-Allow-Headers | preflight | Request headers the script may set | Missing Authorization or Content-Type |
Access-Control-Allow-Credentials | both | Whether cookies / HTTP auth may be sent and the response read | Combining true with Allow-Origin: * (browser rejects it) |
Access-Control-Max-Age | preflight | Seconds the browser may cache the preflight result | Expecting a day; Chromium caps it at 2 hours |
Access-Control-Expose-Headers | actual response | Extra response headers JS may read beyond the safelisted few | Wondering why X-Total-Count or ETag reads as null |
Two of these deserve more than a table row.
Access-Control-Max-Age. Without it, browsers cache a preflight for only about five seconds, which on a chatty single-page app can double your request count. Per MDN's Max-Age reference, Firefox caps the value at 24 hours and Chromium at 2 hours, so Access-Control-Max-Age: 7200 is the practical ceiling for most traffic. The cache is keyed per origin and URL, so a REST design with an ID in every path (/orders/123, /orders/124) still preflights each new URL once.
Access-Control-Expose-Headers. By default a cross-origin script can read only the CORS-safelisted response headers: Cache-Control, Content-Language, Content-Length, Content-Type, Expires, Last-Modified and Pragma. Your pagination cursor in a Link header, a rate-limit Retry-After, or the ETag you need for conditional requests are all invisible to response.headers.get() until you list them.
fetch(url, { credentials: 'include' }) (or withCredentials = true on XHR) asks the browser to attach cookies. The moment you do, the rules tighten:
Access-Control-Allow-Origin must echo the exact requesting origin. * is rejected.Access-Control-Allow-Credentials: true must be present.* in Allow-Headers, Allow-Methods and Expose-Headers stops meaning "anything" and is treated as a literal header or method name.That's deliberate. A wildcard on a public, unauthenticated API (a weather feed, a font CDN) is fine because there is nothing user-specific to leak. A wildcard combined with the user's session cookie would let any website read that user's private data, so the spec forbids the combination outright. Whether you even want cookies on cross-origin API calls is its own design choice; the tradeoffs are laid out in JWT vs. session cookies. If you do, the cookie also needs SameSite=None; Secure for the browser to send it cross-site at all, which is easy to get wrong and quick to check with a SameSite cookie checker.
Since * doesn't work with credentials, a common "fix" copied from Stack Overflow is to read the request's Origin header and echo it back:
// Don't do this
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
next();
});
This is strictly worse than the wildcard. It tells the browser every origin on the internet may make credentialed requests and read the responses, so a malicious page a logged-in user visits can quietly pull their account data. Validate against an explicit allowlist instead, and compare exact strings:
const ALLOWED = new Set([
'https://app.example.com',
'https://admin.example.com',
]);
app.use((req, res, next) => {
const origin = req.headers.origin;
if (origin && ALLOWED.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
res.setHeader('Vary', 'Origin');
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Max-Age', '7200');
return res.sendStatus(204);
}
next();
});
Three details in that snippet matter. Regex allowlists like /example\.com$/ also match evilexample.com, and unanchored patterns match example.com.attacker.net, so prefer exact matches. Never allowlist the literal origin null: sandboxed iframes and some redirects send it, and an attacker can produce it on demand. And Vary: Origin is not optional once the header depends on the request.
Vary: Origin mattersIf your API sits behind a CDN or any shared cache and Access-Control-Allow-Origin varies by caller, the cache needs to know. Without Vary: Origin, the first response gets cached with Allow-Origin: https://app.example.com, and the next caller from https://admin.example.com receives that copy and fails CORS for no visible reason. It is the same cache-key mechanics covered in how Cache-Control, ETag and 304 responses work, just applied to a security header.
Most CORS errors in the console are symptoms, not causes. Checked in roughly this order, these explain the large majority:
Access-Control-Allow-Origin and hides the real status. Open the Network tab, find the request, and look at its status code before touching CORS config.OPTIONS request has no token by design. If authentication runs before CORS handling, the preflight gets a 401 and the real request never fires. Handle OPTIONS before auth.OPTIONS. Load balancers, API gateways and some serverless routers return 405 or 404 for OPTIONS unless configured to pass it through or answer it themselves.Access-Control-Allow-Origin, producing a duplicated value the browser rejects ("contains multiple values").https://app.example.com/), http vs. https, or a forgotten port in local development.And one non-fix to avoid: mode: 'no-cors' doesn't disable CORS. It sends the request and hands your script an opaque response with status 0 and an unreadable body. It is meant for fire-and-forget beacons and caching third-party assets in service workers, not for reading API data.
It's worth stating plainly, because security reviews still get this wrong:
SameSite cookies, CSRF tokens, or require a non-simple content type (which forces a preflight) for state-changing endpoints.curl, scrapers and server-side code.If what you're actually designing is the API surface itself, the CORS policy follows from decisions made earlier, such as whether clients send JSON bodies and custom headers (they will preflight) or stay within form encodings. Those decisions are part of the broader REST vs. RPC tradeoffs.
Treat CORS as a read permission the browser enforces for your users' benefit, not a gate in front of your API. Allowlist exact origins, never reflect Origin with credentials, send Vary: Origin, answer OPTIONS before authentication with a Max-Age of up to 7200 seconds, and expose the response headers your frontend actually needs. When the console shows a CORS error, check the status code first; it is usually a different bug wearing a CORS costume. If you'd rather start from a correct baseline than hand-write the headers, a CORS header builder will generate the nginx, Express or Apache config for a given allowlist, and the MDN CORS guide covers the remaining edge cases.
Free, in your browser, no sign-up.
One email when a new post goes up. No other mail; unsubscribe in one click.
We store your email only to send new posts. See the privacy policy.