← blog · November 9, 2026

Getting CORS Right: Preflight, Credentialed Requests and the Hole Opened by Reflecting Origin

CORS does not block requests, it blocks reading responses; it is neither a server-side firewall nor CSRF protection. Choosing between same origin, an allowlist and a wildcard, an nginx example, and pitfalls from authenticated preflights to a forgotten Vary: Origin.

A browser app calls an API, the console shows a red CORS error, someone adds Access-Control-Allow-Origin: * to the server, the error disappears and the ticket is closed. A few months later a cookie-authenticated API gets "fixed" the same way by echoing whatever Origin arrives, and now any website can read the data of a logged-in user. Most CORS problems come from misunderstanding what the mechanism actually protects. Without that picture, fixes end up either far too permissive or needlessly complicated.

What CORS protects and what it does not

The same-origin policy is a browser rule. An origin is the combination of scheme, host and port, so https://app.example.com and https://api.example.com are different origins. In most cases the browser does not stop a script from sending a request to another origin. What it stops is the script reading the response. CORS is a permission system that lets the server say "these origins may read my responses."

Two consequences follow. First, CORS is not a server-side firewall. curl, a mobile app or another server never looks at these headers, so trying to restrict an API to "only my frontend" with CORS achieves nothing. You still need authentication. Second, CORS is not CSRF protection. A POST that qualifies as a simple request reaches the server and has its side effects; the browser only withholds the response from the script. A money transfer does not get undone because nobody could read the reply.

Simple requests and preflight

Browsers split requests into two groups. GET, HEAD and POST go out directly when they use only safelisted headers and a Content-Type of application/x-www-form-urlencoded, multipart/form-data or text/plain. Those are requests a plain HTML form could already send, so CORS leaves them alone for backward compatibility.

Anything else, such as Content-Type: application/json, an Authorization header, or PUT, PATCH and DELETE, triggers a preflight. The browser sends an OPTIONS request to the same URL with Origin, Access-Control-Request-Method and Access-Control-Request-Headers, effectively asking for permission. Only if the server answers with a successful status and matching permission headers does the real request follow.

Reproducing the preflight by hand is much faster than chasing it in the browser:

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

The response must carry an Access-Control-Allow-Origin value identical to the requesting origin, the requested method and headers must appear in the allow lists, and the status must be 2xx.

Three approaches and when each fits

Make CORS unnecessary. If the frontend and the API can be served from one origin, for instance with a reverse proxy routing /api to the backend, the whole problem goes away. No preflight latency, cookies flow naturally, and there is nothing to misconfigure. If you are building an API for your own frontend, this should be the default. To take a side: a separate api. subdomain is usually created out of habit rather than need, and it brings the full CORS burden with it.

Credentialed CORS with an explicit allowlist. When several frontends on other origins call the same API with cookies, you need a list of permitted origins matched exactly. The server compares the incoming Origin against the list, echoes it back on a match, and adds no CORS headers at all otherwise.

Wildcard for genuinely public data. For an API that serves public data without credentials, such as an open dataset, Access-Control-Allow-Origin: * is the right answer. Browsers refuse the wildcard on credentialed requests, so * simply does not work for a cookie-based API, and that restriction exists to protect you.

A sample configuration

The nginx snippet below implements the allowlist approach. The map block yields the incoming value for known origins and an empty string for everything else; nginx does not send a header whose value is empty.

map $http_origin $cors_origin {
    default "";
    "https://app.example.com"   $http_origin;
    "https://admin.example.com" $http_origin;
}

server {
    location /api/ {
        if ($request_method = OPTIONS) {
            add_header Access-Control-Allow-Origin $cors_origin always;
            add_header Access-Control-Allow-Credentials true always;
            add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE" always;
            add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
            add_header Access-Control-Max-Age 7200 always;
            add_header Vary Origin always;
            return 204;
        }

        proxy_hide_header Access-Control-Allow-Origin;
        add_header Access-Control-Allow-Origin $cors_origin always;
        add_header Access-Control-Allow-Credentials true always;
        add_header Vary Origin always;
        proxy_pass http://backend;
    }
}

The always flag matters: without it, nginx adds add_header values only to successful and redirect responses. proxy_hide_header drops a header the application may set on its own. Do CORS in the proxy or in the application, never in both.

Pitfalls

Reflecting Origin without checking it. On a credentialed API, echoing the incoming Origin unchecked grants the entire internet authenticated read access. If you reflect, compare against an allowlist first.

Loose pattern matching. A rule like "ends with example.com" also accepts evilexample.com. A regex with an unescaped dot lets appXexample.com through. Prefer an exact-match list. If you really need a subdomain pattern, anchor it with https:// at the start and an escaped .example.com at the end, and accept that a takeover of any one of your subdomains now means read access to the whole API.

Allowing the null origin. Sandboxed iframes, file:// pages and some redirects send Origin: null. Adding null to the list for local development means an attacker can produce the same value with a sandboxed iframe.

Putting preflight behind authentication. Browsers never attach cookies or an Authorization header to a preflight. If middleware that authenticates every request answers OPTIONS with 401, the real request is never sent and the console shows only a CORS error. Handle OPTIONS before the authentication layer.

Missing headers on error responses. When the application returns a 500, or the proxy serves its own error page, CORS headers are often absent. The browser hides the response from the script, the developer sees a CORS error instead of the real failure, and debugs the wrong layer. When the console reports CORS, check the actual status code in the network tab first.

Duplicate headers. If both the application and the proxy add Access-Control-Allow-Origin, the browser sees multiple values and rejects the response. This typically happens when CORS is added to a second layer "just to be safe."

Forgetting Vary: Origin. If the permission header changes with the origin but Vary: Origin is missing, a cache in between can serve a response built for one origin to another. The symptom is intermittent CORS errors for some users that nobody can reproduce.

Assuming wildcards work with credentials. On credentialed requests, Access-Control-Allow-Headers: * and Access-Control-Allow-Methods: * are treated as a literal name *, not a wildcard. List headers and methods explicitly.

Unreadable response headers. By default a script can read only safelisted response headers such as Content-Type and Cache-Control. If you return Link for pagination or your own rate limit headers, expose them with Access-Control-Expose-Headers. Otherwise the server sends them and client code sees nothing.

Expecting Max-Age to be honored. Access-Control-Max-Age lets the browser cache the preflight, but browsers cap it. Chromium-based browsers shorten anything above two hours, so writing a one-day value will not make preflights disappear.

When not to enable CORS

Server-to-server integrations do not need CORS at all; adding the headers only widens the attack surface. If you can serve your own frontend from the same origin, fix the routing instead of configuring CORS. And if third-party sites need to call a credentialed API straight from the browser, pause before opening it up: short-lived, narrowly scoped tokens or a backend-to-backend bridge are usually the safer design. Whichever path you take, set up CSRF protection separately with the SameSite cookie attribute, a CSRF token or Origin validation, because CORS does not do that job.