LeepCast
Subscribe
All posts
Security

CORS Explained: Preflight Requests, Credentials, and the Misconfigurations That Leak Data

CORS is a browser rule about who may read a cross-origin response, not a firewall. Here is how simple and preflighted requests work, what credentials change, and how to write an allowlist that does not leak data.

LeepCast7 min read

Almost every web developer meets CORS the same way: a fetch call that works in curl fails in the browser with a red console error, and the quickest fix found online is to add Access-Control-Allow-Origin: * to the server. Sometimes that is fine. Sometimes it quietly opens an API to any website on the internet. Knowing which case you are in requires understanding what CORS actually does, and just as importantly, what it does not do.

What CORS is, and what it is not

Browsers enforce the same-origin policy on scripts. An origin is the combination of scheme, host, and port, so https://app. example. com and https://api. example. com are different origins, and so are http://localhost:3000 and http://localhost:8080. By default, JavaScript running on one origin can send a request to another origin with fetch() or XMLHttpRequest, but it cannot read the response.

Cross-Origin Resource Sharing is the HTTP-header mechanism that lets a server relax that rule. The server tells the browser which other origins are permitted to read its responses, and the browser decides whether to hand the response to the calling script. Three consequences follow from this design and explain most of the confusion around it.

  • CORS is enforced by the browser, not the server. curl, Postman, and backend services ignore it entirely, which is why a request can work everywhere except in a web page.
  • CORS mostly controls reading, not sending. Many cross-origin requests reach your server and execute even when the browser later refuses to show the response to the script.
  • CORS loosens security; it never adds any. Every CORS header you send grants a permission that the same-origin policy would otherwise deny.

When a CORS check fails, the browser deliberately gives JavaScript almost no detail about why. The specific reason appears only in the developer console, so that is the first place to look when debugging.

Simple requests: sent first, checked afterwards

Some cross-origin requests are considered harmless enough that the browser sends them immediately, without asking the server first. MDN calls these simple requests. A request qualifies only if it meets all of the following conditions:

  • The method is GET, HEAD, or POST.
  • The only headers set manually are CORS-safelisted ones: Accept, Accept-Language, Content-Language, Content-Type, and Range with a single byte range.
  • Content-Type, if present, is application/x-www-form-urlencoded, multipart/form-data, or text/plain.
  • No ReadableStream is used as the body, and for XMLHttpRequest no event listeners are registered on the upload object.

These are exactly the kinds of requests an ordinary HTML form could already send long before CORS existed, which is why they are allowed through. The browser adds an Origin header containing the calling page's scheme, host, and port, sends the request, and then checks the response. If the response does not carry an Access-Control-Allow-Origin header matching the caller, the script receives an error instead of the data, but the server has already processed the request.

This is the single most important security point about CORS. A form-encoded POST that transfers money or deletes a record will run on your server regardless of your CORS headers. PortSwigger's Web Security Academy states plainly that CORS is not a protection against cross-site request forgery. Defending against CSRF still requires SameSite cookies, anti-CSRF tokens, or checking the Origin header on the server before acting.

Preflighted requests: asking permission first

Anything outside the simple-request rules triggers a preflight. That includes a PUT or DELETE, a JSON body sent with Content-Type: application/json, or a custom header such as Authorization or X-Request-Id. Before sending the real request, the browser sends an OPTIONS request to the same URL describing what it intends to do:

http
OPTIONS /api/items/42 HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type,authorization

The server answers with what it permits. Only if the method, the headers, and the origin are all allowed does the browser go on to send the actual PUT. The Access-Control-Request-* headers appear only on the preflight, never on the real request.

http
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 7200
Vary: Origin

Caching the preflight

A preflight adds a full network round trip before each qualifying request, which is noticeable on high-latency connections. Access-Control-Max-Age tells the browser how many seconds it may reuse the answer. When the header is absent the default is only 5 seconds, and browsers impose their own ceilings regardless of what you send: according to MDN, Firefox caps the value at 24 hours and Chromium, since version 76, at 2 hours. Sending 7200 therefore sits at the Chromium ceiling and well under Firefox's.

Credentials change the rules

By default, cross-origin fetch calls do not include cookies or HTTP authentication. A script must opt in with credentials: "include" in fetch, or withCredentials = true on XMLHttpRequest. Once it does, the server has to opt in as well, and the rules become stricter:

  • The response must include Access-Control-Allow-Credentials: true, or the browser discards it.
  • Access-Control-Allow-Origin must name one explicit origin. A literal * is rejected, and any Set-Cookie in that response is ignored.
  • Access-Control-Allow-Headers, Access-Control-Allow-Methods, and Access-Control-Expose-Headers must also be explicit lists rather than *.
  • The preflight itself never carries credentials, but its response must still say Access-Control-Allow-Credentials: true for the real request to include them.

Even with every header correct, cookies may still not be sent. Third-party cookie policies and the cookie's own SameSite attribute are applied independently of CORS, so a cookie set with SameSite=Lax or Strict will not accompany a cross-site fetch no matter what the server allows.

Because Access-Control-Allow-Origin accepts only a single origin or *, a server that serves several front ends has to pick the right origin per request. When it does that, it must also send Vary: Origin. Without it, a CDN or shared cache can store the response generated for one origin and serve it to another, producing either mysterious CORS failures or permissions granted to the wrong site.

The misconfigurations that leak data

The dangerous combination is credentials plus a permissive origin check. An attacker's page can then make the victim's browser send authenticated requests and read the answers, which is exactly what the same-origin policy exists to prevent. PortSwigger's guide to CORS vulnerabilities describes several recurring patterns:

  1. Reflecting the Origin header. The server copies whatever Origin it receives into Access-Control-Allow-Origin and adds Access-Control-Allow-Credentials: true. This is equivalent to trusting every website on the internet.
  2. Loose string matching. An allowlist implemented with startsWith, endsWith, or an unanchored regular expression accepts origins like https://example. com. attacker. net or https://notexample. com.
  3. Trusting the null origin. Browsers send Origin: null in several situations, including sandboxed iframes, which an attacker can create at will. Allowing null effectively allows anyone.
  4. Trusting insecure or weak siblings. Allowing an http:// origin, or a subdomain with an XSS flaw, lets an attacker who controls that origin read data from the trusting site.
  5. Wildcards on internal services. An intranet API that answers with Access-Control-Allow-Origin: * can be read by any public page a victim opens while on the internal network, using their browser as a proxy.

Exact string comparison against a fixed allowlist of full origins is the only matching strategy that is easy to get right.

A correct implementation in plain Node. js

The example below uses only Node's built-in http and crypto modules, so it runs with no dependencies. Save it as server. mjs and start it with node server. mjs. It allows two exact origins with credentials, answers preflights, caches them for two hours, exposes one custom response header, and always sends Vary: Origin.

javascript
import { createServer } from "node:http";
import { randomUUID } from "node:crypto";

const ALLOWED_ORIGINS = new Set([
  "https://app.example.com",
  "https://admin.example.com",
]);

const server = createServer((req, res) => {
  const origin = req.headers.origin;
  const allowed = origin !== undefined && ALLOWED_ORIGINS.has(origin);

  // The response depends on Origin, so shared caches must key on it.
  res.setHeader("Vary", "Origin");

  if (allowed) {
    res.setHeader("Access-Control-Allow-Origin", origin);
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Expose-Headers", "X-Request-Id");
  }

  const isPreflight =
    req.method === "OPTIONS" &&
    req.headers["access-control-request-method"] !== undefined;

  if (isPreflight) {
    if (allowed) {
      res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
      res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
      res.setHeader("Access-Control-Max-Age", "7200");
    }
    res.writeHead(204);
    res.end();
    return;
  }

  res.setHeader("X-Request-Id", randomUUID());
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ ok: true, path: req.url }));
});

server.listen(8080, () => console.log("listening on http://localhost:8080"));

Note what the code does not do. It never echoes an unchecked Origin, never uses pattern matching, and never treats null as a valid origin, because a Set lookup on the full string accepts only the exact entries listed. A disallowed origin still receives a normal response, just without any Access-Control headers, so the browser blocks the read. Rejecting it with an error status is optional and mostly a matter of taste.

You can simulate a preflight from the command line and inspect the headers the server returns:

bash
curl -i -X OPTIONS http://localhost:8080/api/items/42 \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: PUT" \
  -H "Access-Control-Request-Headers: content-type,authorization"

Run the same command with Origin: https://evil. example and the response will contain Vary: Origin but no Access-Control-Allow-Origin, which is exactly what a browser needs to refuse the cross-origin read.

A short CORS checklist

  • Do you need CORS at all? Serving the front end and API from the same origin, for example behind one reverse proxy path, avoids the problem entirely.
  • Use * only for genuinely public, unauthenticated data such as open datasets or public fonts, and never on internal services.
  • Match origins by exact string against a fixed allowlist; never reflect, prefix-match, suffix-match, or allow null.
  • Send Vary: Origin whenever Access-Control-Allow-Origin is chosen per request.
  • Allow only the methods and headers your API actually uses, and set Access-Control-Max-Age to cut preflight latency.
  • Keep CSRF defenses in place, because simple requests reach your server whatever your CORS policy says.
  • Remember that CORS protects browsers only; authentication and authorization on the server remain mandatory.

Treated this way, CORS stops being an obstacle to silence and becomes what it was designed to be: a narrow, explicit list of the sites you trust to read your users' data.

Share

Enjoyed this?

Get the next deep dive in your inbox. No spam — just the stories worth reading.

Subscribe to the newsletter

Comments