Your API at https://api.myapp.com serves the page at https://myapp.com. On the first day after deploy, the console (the message panel in DevTools) fills with red errors: blocked by CORS policy. The temptation is to set * (a star, meaning every site) so the errors go away. Yet * is the value of a header, and that header decides whether other sites may read your users' data.
CORS (Cross-Origin Resource Sharing) is how a server tells the browser: "pages from this origin may read my answer." Without that permission, JavaScript on a page from another origin can still send a request, but the browser won't give the answer (the response) to that JavaScript. Picture an office receptionist. A letter from any visitor is still taken inside and answered. But the receptionist only gives the reply to the visitor when the envelope says "may be given to visitors from office X". The receptionist is the browser, the visitor is the JavaScript on the page, and the people inside the office are the server. The note on the envelope is the Access-Control-Allow-Origin header, and office X is the allowed origin.
Origin: scheme, host, port
An origin is three parts of a URL put together: the scheme (https, also called the protocol), the host (myapp.com), and the port (443, the default for https). Two URLs share an origin when all three are exactly the same. A path (the part after the host) like /orders doesn't count.
| URL | Same as https://myapp.com? |
Why |
|---|---|---|
https://myapp.com/orders |
same | only the path differs |
http://myapp.com |
different | scheme http, not https |
https://api.myapp.com |
different | different host, a subdomain counts as different too |
https://myapp.com:8080 |
different | port 8080, not 443 |
Browsers apply the same-origin policy, the same-origin rule you met in the CSRF lesson: JavaScript on a page may only read answers from its own origin. A page on https://myapp.com calling https://api.myapp.com is already cross-origin. So the API has to allow it through CORS.
What the browser holds back: the answer, not the request
For a simple request such as GET, the browser sends it right away. The browser adds an Origin header, which holds the origin of the page that sends it. This is a request from a page on https://evil.com:
GET /orders HTTP/1.1
Host: api.myapp.com
Origin: https://evil.com
The server processes that request and answers 200 OK with the data. Only after the answer arrives does the browser check the Access-Control-Allow-Origin header in that answer:
- It equals the page's origin, or is
*: JavaScript may read the answer. - The header is missing, or names another origin: the browser holds the answer back. In Chrome,
fetchfails withTypeError: Failed to fetch, and the console says:
Access to fetch at 'https://api.myapp.com/orders' from origin 'https://evil.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
So even when your API sets no CORS header at all, the request from https://evil.com still reaches the server and gets answered. Only the answer is held back, so the JavaScript on evil.com can't read it. That's why CORS is no replacement for login: the server still has to check who is asking.
Preflight: the browser asks first
A request such as DELETE isn't sent right away. The browser asks first with an OPTIONS request. This asking request is called the preflight:
OPTIONS /orders/7 HTTP/1.1
Host: api.myapp.com
Origin: https://myapp.com
Access-Control-Request-Method: DELETE
The Access-Control-Request-Method header names the method the page wants to use. A server that allows it answers like this:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 7200
Access-Control-Allow-Methods and Access-Control-Allow-Headers name the methods and headers that may be used. If the origin and the method are allowed, the browser then sends the real DELETE /orders/7. If not, the real request is never sent, so order #7 is safe.
The preflight is skipped only for a simple request, one that meets all of these conditions:
- its method is
GET,HEAD, orPOST; - its headers are only the ones the browser considers safe, such as
AcceptandContent-Type, with noAuthorizationor headers of your own; - its
Content-Type(if any) isapplication/x-www-form-urlencoded,multipart/form-data, ortext/plain.
So PUT, DELETE, an Authorization header, and Content-Type: application/json all trigger a preflight. Access-Control-Max-Age says for how many seconds the browser may remember the preflight answer, so it doesn't ask again on every request. Chrome caps it at 7,200 seconds (2 hours), Firefox at 86,400 seconds (24 hours).
Setting CORS headers on the server
The server decides per request: is the asking origin on the allowlist or not? This is the same function as in the exercise. The lower part tries the function with two origins:
function setCORSHeaders(res, origin, allowedOrigins) {
if (allowedOrigins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
}
// any other origin: gets no header at all
}
const headers = {};
const res = { setHeader(name, value) { headers[name] = value; } };
setCORSHeaders(res, "https://myapp.com", ["https://myapp.com", "https://admin.myapp.com"]);
console.log("Access-Control-Allow-Origin:", headers["Access-Control-Allow-Origin"]);
console.log("Access-Control-Allow-Methods:", headers["Access-Control-Allow-Methods"]);
console.log("Access-Control-Allow-Headers:", headers["Access-Control-Allow-Headers"]);
const headers2 = {};
const res2 = { setHeader(name, value) { headers2[name] = value; } };
setCORSHeaders(res2, "https://evil.com", ["https://myapp.com"]);
console.log("Blocked origin headers:", JSON.stringify(headers2));
Its output:
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Blocked origin headers: {}
reshere is a stand-in response:setHeader(name, value)just records the header in theheadersobject. In Express, the realres.setHeaderis called the same way.allowedOrigins.includes(origin)matches the origin exactly, character for character. Sohttps://myapp.com.evil.comdoesn't pass.- An allowed origin is reflected (written back as it is) into
Access-Control-Allow-Origin, because that header may hold only one origin (or*). https://evil.comisn't on the list, soheaders2stays empty andJSON.stringify(headers2)returns{}.
For a real server, this function still misses one header: Vary: Origin, a sign that the answer differs per origin. Without it, a cache (the browser cache, a CDN or a proxy) may store one answer and give it to another origin. For example:
https://myapp.comasks for the data first.- The answer with
Access-Control-Allow-Origin: https://myapp.comis stored in the cache. https://admin.myapp.comreceives that stored answer, and the browser blocks it because the origin does not match.
Write Vary at the start of the function, outside the if. The reason: the answer differs per origin, whether that origin is allowed or not:
function setCORSHeaders(res, origin, allowedOrigins) {
res.setHeader("Vary", "Origin"); // always, outside the if
if (allowedOrigins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
}
}
In Chromium (the browser engine of Chrome), with an answer that may be cached for 60 seconds: without Vary, the second origin gets the answer from the cache, and its fetch fails with Failed to fetch. With Vary: Origin, the browser asks the server again and the request succeeds.
Credentials: when cookies are sent too
By default, a cross-origin fetch carries no cookies. To send them, the page writes fetch(url, { credentials: 'include' }). Credentials here means cookies and other login data the browser sends automatically. The server's answer then has to meet two conditions:
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Credentials: truemust be there.Access-Control-Allow-Originmust be the exact origin, not*. The browser refuses*combined with credentials with the messageThe value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
So Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true is a broken configuration: your own app fails to read the answer. The real danger comes from the wrong "fix", which is reflecting any origin without checking it. That lets every site read the logged-in user's data.
💡 In Express and Laravel
You usually don't write CORS headers by hand. Express has the cors package with similar options: origin, methods, allowedHeaders, credentials and maxAge. In Laravel, CORS is built in. Its rules are in config/cors.php. Since Laravel 11, you create that file with php artisan config:publish cors:
return [
'paths' => ['api/*'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'],
'allowed_origins' => ['https://myapp.com', 'https://admin.myapp.com'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['Content-Type', 'Authorization'],
'exposed_headers' => [],
'max_age' => 7200,
'supports_credentials' => true,
];
The cors package and Laravel both match the origin against the list, then add Vary: Origin to the answer, so caches such as a CDN don't serve an answer meant for one origin to another.
⚠️ CORS mix-ups that leak data
- Reflecting any origin.
res.setHeader("Access-Control-Allow-Origin", req.headers.origin)with no list check, especially withAccess-Control-Allow-Credentials: true, is the same as letting every site read the logged-in user's data. Check first withallowedOrigins.includes(origin). *with credentials. The browser refuses it. Replace*with the exact origin from the allowlist.- Giving a refused origin headers anyway. When the origin isn't on the list, set no CORS header at all, Methods and Headers included. In the exercise,
JSON.stringify(headers2)must be{}. - Thinking CORS protects the server. CORS is only the browser's rule about who may read an answer.
curl, Postman, and other servers ignore CORS, and simple requests still arrive. Your endpoint still needs login and permission checks.
TL;DR: CORS (Cross-Origin Resource Sharing) is the server's permission for JavaScript on another origin to read its answer (the response). Origin = scheme + host + port, so https://api.myapp.com is a different origin from https://myapp.com. A simple request (GET) still reaches the server. The browser only holds the answer back when the Access-Control-Allow-Origin header doesn't match the page's origin. DELETE, PUT, an Authorization header or a JSON body trigger a preflight first: an OPTIONS request that asks the server. When the preflight is refused, the real request is never sent. On the server, write the page's origin into Access-Control-Allow-Origin (reflect the origin) only when it is on the allowlist: allowedOrigins.includes(origin). Then also set the Methods and Headers headers (the methods and headers that may be used). Every other origin gets no header at all. When cookies are sent (credentials: 'include'), the answer needs Access-Control-Allow-Credentials: true and the exact origin, never * (every origin).
⚡ Origin: scheme, host, port
Meaning: An origin is the scheme (https), host and port put together. Two URLs share an origin when all three are exactly the same. https://api.myapp.com is a different origin from https://myapp.com, so the API on api.myapp.com has to allow the page on myapp.com through CORS: a header from the server that lets JavaScript on another origin read its answer (the response).
⚡ The answer is held back, not the request
Meaning: A simple request such as GET still reaches the server and gets answered. The browser only holds the answer back when the Access-Control-Allow-Origin header doesn't match the page's origin. That's why CORS is no replacement for login. A request such as DELETE comes after a preflight, an OPTIONS request that asks the server first. If the preflight is refused, the real request is never sent.
⚡ An allowlist of origins
Write:
if (allowedOrigins.includes(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
}
Meaning: origin is the origin of the page that asks, and allowedOrigins is the list of allowed origins (the allowlist). When the origin is exactly on the list, it is written into the Access-Control-Allow-Origin header. An origin not on the list gets no CORS header at all.
⚡ Credentials and the wildcard
Guess first: * means every origin, and credentials means cookies are sent. What's wrong with Access-Control-Allow-Origin: * together with Access-Control-Allow-Credentials: true?
The browser refuses a wildcard origin (*) with credentials, so your own app can't read the answer.
Meaning: When cookies are sent, use the exact origin from the allowlist, not *. Never write an origin into the header without checking it first.