How to Handle CORS Preflight and Credentials
Configure CORS correctly for browser clients: respond to preflight, allow only intended origins, handle credentials, and expose response headers.
On this page
Introduction
Cross-Origin Resource Sharing is the browser mechanism that decides whether JavaScript running on one origin may read a response from another. It is a frequent source of confusion because the rules are enforced by the browser, not the server, and because credentialed requests behave differently from anonymous ones. A misconfiguration either blocks a legitimate front-end or opens a hole, and the failure often appears only in the browser, not in curl, which makes it hard to debug.
This tutorial configures CORS for a Node.js API serving a single-page client on a different origin. It explains when the browser sends a preflight, how to answer it, why a wildcard origin is incompatible with credentials, how to expose response headers, and how to test the three cases — preflight, allowed actual request, and blocked request — with a real browser.
Understand simple versus preflighted requests
The browser classifies a cross-origin request as simple or preflighted. A simple request uses a limited set of methods and headers and can be sent directly, with the response exposed only if the server allows the origin. A preflighted request uses a non-simple method such as PUT or DELETE, a custom header such as Authorization or Content-Type: application/json, and the browser first sends an OPTIONS request to ask permission. If that preflight is not answered correctly, the actual request never leaves the browser.
This is why a front-end can read a GET with no custom headers while a POST with a JSON body fails. The preflight is the difference. The server must answer the OPTIONS request with the methods and headers it permits, the origin allowed, and optionally a max-age so the browser caches the decision and skips future preflights for a while.
const ALLOWED = new Set(['https://app.example.com', 'https://admin.example.com']);
function applyCors(req, res) {
const origin = req.headers.origin;
if (!origin) return false;
if (!ALLOWED.has(origin)) return false; // no CORS headers -> browser blocks
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Vary', 'Origin');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Request-ID');
res.setHeader('Access-Control-Max-Age', '600');
if (req.method === 'OPTIONS') {
res.writeHead(204);
res.end();
return true;
}
return false;
}
Reflect only allowed origins
The Access-Control-Allow-Origin header must be either a single origin or the literal star. Echoing the request origin from an allowlist is the common pattern, but it must be an actual allowlist comparison, not a reflection of whatever the client sends. Reflecting any origin is equivalent to the star for anonymous requests and defeats the purpose for credentialed ones, because it lets any site read responses.
Always add Vary: Origin when the allowed origin depends on the request. Without it, a shared cache may store the response with one origin’s allow header and serve it to a request from another origin, causing intermittent, hard-to-reproduce failures. The Vary header tells caches that the origin is part of the cache key.
Credentialed requests and the wildcard trap
When a request includes cookies, TLS client certificates, or the Authorization header set by a script with credentials, the browser treats it as credentialed. The CORS specification forbids combining credentials with a wildcard origin. If the server sends Access-Control-Allow-Origin: * and the request is credentialed, the browser rejects the response. The server must echo the exact origin and set Access-Control-Allow-Credentials: true.
Set Allow-Credentials only for origins you trust. The header is a promise that the browser may expose credentialed responses to that origin, so pairing it with a broad allowlist invites cross-site request forgery from any allowed site. Keep the allowlist tight and never derive it from user input.
function applyCredentials(req, res) {
const origin = req.headers.origin;
if (origin && ALLOWED.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin); // never '*'
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Vary', 'Origin, Access-Control-Request-Headers');
}
}
Expose the response headers clients need
By default a browser hides almost all response headers from cross-origin JavaScript; the script can read only a small CORS-safelisted set such as Content-Type. If your client needs a custom header like X-RateLimit-Remaining or a pagination Link header, the server must list it in Access-Control-Expose-Headers. This is easy to forget because the header is present on the wire and visible in devtools, yet undefined in the fetch Response object.
Expose the narrowest set that the client actually uses. Listing every header, or using a wildcard where credentials are involved, widens what a compromised script on an allowed origin can read.
res.setHeader('Access-Control-Expose-Headers', 'X-RateLimit-Remaining, X-Request-ID, Link');
Test with a browser, not only curl
Because CORS is enforced by the browser, testing with curl proves nothing about whether the front-end will work. curl never sends an Origin header and never enforces the allow rules, so a fully broken CORS configuration returns 200 to curl. Test in a browser or a headless browser: confirm the preflight returns 204 with the expected allow headers, confirm the actual request succeeds and the script can read an exposed header, and confirm a request from a disallowed origin is blocked by the browser.
Automate at least the server-side half. Send an OPTIONS with the actual Origin and Access-Control-Request-Headers and assert the response echoes the origin, lists the requested header, and does not use a wildcard. Then send a request with a disallowed origin and assert no allow-origin header is present, which is what makes the browser block it.
curl -sD - -o /dev/null -X OPTIONS http://localhost:3000/api/orders \
-H 'Origin: https://app.example.com' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: content-type,authorization'
# expect 204 with Access-Control-Allow-Origin echoing the origin and Vary: Origin
Common pitfalls
Using a wildcard with credentials, reflecting any origin, omitting Vary: Origin, forgetting to expose custom headers, and treating CORS as server-side authorization are the five mistakes that recur. The last is the dangerous one: CORS protects the browser user, not the API. A mobile client or a server-to-server call ignores it entirely, so authentication and authorization must always be enforced independently on the server.
Conclusion
Handle preflight by answering OPTIONS with the allowed methods, headers, and a max-age. Echo only origins from an explicit allowlist, add Vary: Origin, and never combine a wildcard origin with credentials. Expose just the response headers the client reads, and test with a browser because curl cannot see the enforcement. Self-check by issuing an OPTIONS preflight from an allowed origin and asserting the response is 204 with a reflected origin, then repeating from a disallowed origin and asserting the absence of allow-origin.
Keep the CORS policy in one middleware so the allowlist and the credential decision live in a single reviewed place.
Sources: MDN: Cross-Origin Resource Sharing (CORS), Fetch standard: CORS protocol, MDN: Access-Control-Allow-Credentials.
FAQ
- Why does my credentialed request fail even though the GET works?
- A credentialed cross-origin request cannot use a wildcard origin. The browser requires Access-Control-Allow-Origin to echo the exact request origin and Access-Control-Allow-Credentials: true. Sending * with credentials is rejected by design.
- Is CORS a server-side security boundary?
- No. CORS is enforced by the browser to protect users, not the server. A non-browser client ignores it entirely, so it never replaces authentication and authorization on the server.
Report a problem with this articleOpens a pre-filled issue on GitHub.