← Back to blog
A small glowing blue sphere on a dark glass platform sends a thin beam through a tall translucent glass panel, where it widens into a bright blue beam reaching a second platform of glowing cubes.
Security·November 24, 2026·9 min read

CORS Explained: Preflight, Credentials, and What It Doesn't Protect

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.

The rule CORS relaxes: same-origin policy

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.

Simple requests vs. preflighted requests

The Fetch spec splits cross-origin requests into two kinds, and the split is where most surprises live.

Simple requests go out immediately

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.

Everything else gets a preflight

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:

Browser (app.example.com) API (api.example.com) 1. OPTIONS /orders (no cookies, no auth) Origin + Access-Control-Request-Method: PUT + Request-Headers: content-type 2. 204 No Content Allow-Origin, Allow-Methods, Allow-Headers, Max-Age check + cache result 3. PUT /orders (Origin, body, credentials if asked) 4. 200 OK + Access-Control-Allow-Origin expose to JS or block

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.

The response headers, and what each actually controls

HeaderSent onWhat it controlsCommon mistake
Access-Control-Allow-Originpreflight and actual responseWhich single origin (or *) may read the responseListing several origins in one value; only one is allowed
Access-Control-Allow-MethodspreflightMethods allowed for the real requestForgetting PATCH or DELETE
Access-Control-Allow-HeaderspreflightRequest headers the script may setMissing Authorization or Content-Type
Access-Control-Allow-CredentialsbothWhether cookies / HTTP auth may be sent and the response readCombining true with Allow-Origin: * (browser rejects it)
Access-Control-Max-AgepreflightSeconds the browser may cache the preflight resultExpecting a day; Chromium caps it at 2 hours
Access-Control-Expose-Headersactual responseExtra response headers JS may read beyond the safelisted fewWondering 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.

Credentials: where the wildcard stops working

fetch(url, { credentials: 'include' }) (or withCredentials = true on XHR) asks the browser to attach cookies. The moment you do, the rules tighten:

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.

The vulnerability: reflecting Origin blindly

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.

Why Vary: Origin matters

If 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.

Debugging the errors browsers actually show

Most CORS errors in the console are symptoms, not causes. Checked in roughly this order, these explain the large majority:

  1. The server returned an error without CORS headers. A 401, 404 or 500 generated by a framework's error handler often skips the middleware that adds CORS headers. The browser then reports a missing 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.
  2. Auth middleware rejects the preflight. The 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.
  3. A proxy or gateway eats 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.
  4. Headers are set twice. The app and the reverse proxy both add Access-Control-Allow-Origin, producing a duplicated value the browser rejects ("contains multiple values").
  5. Origin mismatch on a technicality. A trailing slash in your allowlist (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.

What CORS is not

It's worth stating plainly, because security reviews still get this wrong:

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.

Takeaway

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.

#cors#preflight#same-origin-policy#web-security#http-headers#api-design
ShareXLinkedInHacker News

Try it

Free, in your browser, no sign-up.

New posts by email

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.

Related reading

Security
JWT vs Session Cookies: The Trade Isn't Statelessness, It's Revocation
API Design
HTTP Caching Explained: Cache-Control, ETag and 304 Not Modified
Data Formats
JSON Patch vs JSON Merge Patch: Picking a PATCH Format That Won't Lose Data