- The rule CORS relaxes
- Simple requests and preflighted requests
- The response headers, one by one
- Reading the error messages
- Working configurations
- Mistakes that open a hole
- When you do not need CORS at all
- A checklist for the next CORS error
Your API works in Postman, works in curl, and fails in the browser with a red line about Access-Control-Allow-Origin. That is CORS, and almost every developer meets it the same way: as an error that makes no sense, on a request that plainly works everywhere else.
This guide explains what the browser is actually checking, which requests trigger a preflight, what each response header does, and how to read the error messages so you fix the right thing. It ends with configs you can copy for Express, Laravel, plain PHP and nginx, and the mistakes that turn a CORS fix into a security hole.
The rule CORS relaxes
Browsers enforce the same-origin policy. A script loaded from one origin cannot read responses from another origin unless that other origin says it may.
An origin is three things together: scheme, host and port. Change any one of them and you have a different origin.
| URL | Same origin as https://app.example.com? |
|---|---|
https://app.example.com/orders |
Yes, only the path differs |
http://app.example.com |
No, different scheme |
https://api.example.com |
No, different host |
https://app.example.com:8443 |
No, different port |
http://localhost:5173 and http://localhost:8000 |
Different from each other, the ports differ |
The policy exists because browsers attach your cookies to requests automatically. Without it, any page you visited could quietly call your bank's API from your browser, as you, and read the reply.
CORS, short for Cross-Origin Resource Sharing, is the opt-out. It is a set of response headers a server uses to tell the browser which other origins are allowed to read its responses. Two consequences follow from that, and they clear up most of the confusion.
First, the server grants access but the browser does the enforcing. curl, Postman and your backend code never look at CORS headers, which is why the request "works everywhere else".
Second, CORS is fixed on the server that receives the request. Nothing you change in the frontend code that makes the call will add a header to someone else's response.
Simple requests and preflighted requests
The browser sorts every cross-origin request into one of two groups.
Simple requests
A request is "simple" when it looks like something a plain HTML form could already send. That means:
- the method is
GET,HEADorPOST - the only headers you set yourself are from a short safelist:
Accept,Accept-Language,Content-Language,Content-TypeandRange Content-Type, if present, isapplication/x-www-form-urlencoded,multipart/form-dataortext/plain
The browser sends a simple request straight away, with an Origin header added:
GET /products HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
If the response allows that origin, your script gets the data:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Content-Type: application/json
If the header is missing or names a different origin, the browser throws the response away and your fetch() rejects. Notice what did not happen: the request was not blocked. It reached your server and your server ran it. CORS only stopped the script from reading the answer. A simple cross-origin POST that deletes a record still deletes the record, which is one reason CORS is no defence against cross-site request forgery.
Preflighted requests
Anything that is not simple gets a preflight. In practice that covers most API calls, because any one of these is enough to trigger it:
- a method such as
PUT,PATCHorDELETE Content-Type: application/json- a custom header, including
Authorization
Before sending the real request, the browser sends an OPTIONS request to the same URL asking for permission:
OPTIONS /orders/42 HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization, content-type
The server answers with what it allows:
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: Authorization, Content-Type
Access-Control-Max-Age: 7200
Only if the method and every requested header are covered does the browser send the real PUT. The real response then needs Access-Control-Allow-Origin as well. People often get the preflight right and forget this second half.
Two details about preflights cause a lot of lost afternoons. A preflight never carries cookies or an Authorization header, so if your auth middleware runs before your CORS handling, it rejects the OPTIONS request with a 401 and the browser reports a CORS failure. And the preflight response must have a 2xx status. A 404 because no OPTIONS route exists, or a redirect to a login page, fails the check even if every header is perfect.
The response headers, one by one
Access-Control-Allow-Origin
The one header every cross-origin response needs. It takes exactly one value: a single origin, or * for any origin.
Access-Control-Allow-Origin: https://app.example.com
You cannot list several origins, and you cannot use a partial wildcard like https://*.example.com. To allow more than one origin, the server checks the incoming Origin header against its own allowlist and echoes back the one that matched.
When the value changes depending on who asked, also send Vary: Origin. Without it, a CDN or the browser cache can store the response it produced for one origin and serve it to another, which then fails. The guide to HTTP caching headers covers how Vary shapes the cache key.
Access-Control-Allow-Methods and Access-Control-Allow-Headers
These only matter on the preflight response. They list the methods and request headers the real request may use. Header names are case-insensitive, so authorization matches Authorization.
Access-Control-Allow-Credentials
By default a cross-origin fetch() sends no cookies. To send them, the frontend has to ask:
const response = await fetch('https://api.example.com/me', {
credentials: 'include',
});
With Axios the equivalent option is withCredentials: true. Either way, the server has to agree:
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Once credentials are involved, wildcards are off the table. Access-Control-Allow-Origin: * is rejected for a credentialed request, and the same goes for * in the allowed methods and headers. You must name the origin.
The cookie has its own rules on top of this. app.example.com calling api.example.com is cross-origin but same-site, so an ordinary SameSite=Lax cookie is still sent. Calling an API on an unrelated domain is cross-site, and the cookie needs SameSite=None; Secure before the browser will attach it at all.
Access-Control-Expose-Headers
A script reading a cross-origin response only sees a handful of response headers by default, such as Content-Type and Cache-Control. If your frontend needs to read X-Total-Count, a rate limit header or ETag, the server has to expose it:
Access-Control-Expose-Headers: X-Total-Count, ETag
This one catches people because the header is right there in the Network tab, yet response.headers.get('X-Total-Count') returns null.
Access-Control-Max-Age
How long, in seconds, the browser may cache a preflight result. The default is only 5 seconds, so without this header nearly every API call costs two round trips.
Browsers cap the value. Firefox allows up to 86,400 seconds (24 hours) and Chromium-based browsers cap it at 7,200 seconds (2 hours). Setting 7,200 gets you the most that Chrome will honour.
Reading the error messages
Chrome's console messages are specific once you know what each one is pointing at. These are the ones you will meet most.
"No 'Access-Control-Allow-Origin' header is present on the requested resource." The response had no CORS header at all. Either CORS is not configured for that route, or the request died before your CORS code ran. A 500 from an unhandled exception, a 502 from the proxy and a 404 from a mistyped URL all produce this message, because error pages rarely carry CORS headers. Check the status code in the Network tab before touching any CORS config.
"Response to preflight request doesn't pass access control check: It does not have HTTP ok status." The OPTIONS request got a non-2xx response. Usually your router has no handler for OPTIONS, or authentication ran first and returned 401.
"Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response." The preflight succeeded but did not list a header you are sending. Add it to the allowed headers.
"The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'." You are sending cookies to an API that answers with *. Echo the specific origin and add Access-Control-Allow-Credentials: true.
"The 'Access-Control-Allow-Origin' header contains multiple values." Two layers are both adding the header, typically nginx and the application behind it. Pick one place to handle CORS and remove the other.
To see exactly what the server says without a browser in the way, replay the preflight with curl:
curl -i -X OPTIONS https://api.example.com/orders/42 \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: PUT" \
-H "Access-Control-Request-Headers: authorization, content-type"
You want a 2xx status and the four Access-Control-* headers from the preflight example above. If curl shows them and the browser still complains, compare the Origin value character by character. A trailing slash, http instead of https, or a missing port is enough to fail the match.
One thing that is not a fix: mode: 'no-cors'. It does make the error disappear, because the browser hands you an opaque response with no status, no headers and no body. The request goes out and you can read nothing back.
Working configurations
All four examples do the same job: allow a named list of origins, support credentials, and answer preflights.
Express
The cors package handles preflights and sets Vary: Origin for you.
import express from 'express';
import cors from 'cors';
const app = express();
app.use(cors({
origin: ['https://app.example.com', 'http://localhost:5173'],
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
exposedHeaders: ['X-Total-Count'],
credentials: true,
maxAge: 7200,
}));
Register it before your authentication middleware so preflights are answered before anything asks for a token.
Laravel
Laravel ships a HandleCors middleware in the global stack and answers OPTIONS requests for you. Publish the config file, then edit it:
php artisan config:publish cors
// config/cors.php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => [
'https://app.example.com',
'http://localhost:5173',
],
'allowed_origins_patterns' => [],
'allowed_headers' => ['Content-Type', 'Authorization', 'X-Requested-With'],
'exposed_headers' => ['X-Total-Count'],
'max_age' => 7200,
'supports_credentials' => true,
];
The paths key is the usual culprit when this appears not to work. A route outside those patterns gets no CORS headers at all.
Plain PHP
Without a framework, check the origin against an allowlist and answer the preflight yourself.
<?php
$allowed = ['https://app.example.com', 'http://localhost:5173'];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowed, true)) {
header("Access-Control-Allow-Origin: {$origin}");
header('Access-Control-Allow-Credentials: true');
header('Vary: Origin');
}
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Max-Age: 7200');
http_response_code(204);
exit;
}
Note the strict comparison against a fixed list. The origin is only echoed back when it is one you already trust.
nginx
Handling CORS at the proxy keeps it out of your application. A map turns the allowlist into a variable that is empty for unknown origins, and nginx skips any add_header whose value is empty.
map $http_origin $cors_origin {
default "";
"https://app.example.com" $http_origin;
"http://localhost:5173" $http_origin;
}
server {
location /api/ {
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Vary "Origin" always;
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 "Content-Type, Authorization" always;
add_header Access-Control-Max-Age 7200 always;
add_header Vary "Origin" always;
return 204;
}
proxy_pass http://127.0.0.1:8000;
}
}
The always flag matters. Without it nginx only adds the headers to successful responses, so every 4xx and 5xx from your API shows up in the browser as a CORS error and hides the real problem. The headers are repeated inside the if block because add_header directives from the outer level are not inherited once a block defines its own.
If you configure CORS here, switch it off in the application. Doing it in both places gives you the "multiple values" error.
Mistakes that open a hole
CORS loosens a browser protection, so a careless config gives away more than you meant to.
Reflecting any origin with credentials. Code that copies whatever Origin arrived into Access-Control-Allow-Origin, with Access-Control-Allow-Credentials: true alongside it, lets any website read your logged-in users' data. It is the wildcard the browser forbids, rebuilt by hand. Always compare against an allowlist.
Loose matching. Checking that the origin ends with example.com also accepts evilexample.com. Checking that it contains example.com accepts example.com.attacker.net. Compare whole origins, or anchor a regular expression at both ends.
Allowing the null origin. Sandboxed iframes and local files send Origin: null. An allowlist that includes null trusts every one of them.
Treating CORS as access control. CORS decides which web pages may read a response in a browser. It does nothing about scripts, servers or anyone with curl. Your API still needs real authentication on every request, whether that is a session cookie or a JWT.
A plain Access-Control-Allow-Origin: * is not on this list. For public, read-only data that needs no login, such as a font file or an open dataset, the wildcard is the correct setting.
When you do not need CORS at all
The cheapest CORS config is none. If the browser only ever talks to one origin, the same-origin policy never comes into it.
In development, have the dev server proxy API calls. With Vite:
// vite.config.js
export default {
server: {
proxy: {
'/api': 'http://localhost:8000',
},
},
};
Your frontend calls /api/orders on its own origin and Vite forwards the request. No preflight, no headers.
In production the same idea is a reverse proxy: serve the frontend at https://example.com and route https://example.com/api/ to the backend. You also save the preflight round trip on every uncached call, which is a real cost on slow mobile connections.
Keep CORS for the cases that need it: a public API used by other people's sites, or a frontend and backend that live on separate domains for good reasons.
A checklist for the next CORS error
- Open the Network tab and read the status code of the failed request. If it is a
4xxor5xx, fix that first. - Look for an
OPTIONSrequest just before it. If there is one, that is the response to inspect. - Replay the preflight with curl and read the headers the server really sends.
- Compare
Access-Control-Allow-Originwith your page's origin exactly: scheme, host and port. - If cookies are involved, confirm
credentials: 'include'on the request,Access-Control-Allow-Credentials: trueon the response, and a named origin in place of*. - Make sure only one layer is adding the headers.