Sub topic 10
Cross-Origin Requests, CORS, and Cookies
This chapter assumes you can already make GET and POST requests with fetch, check response.ok, set headers with the Headers interface, and send JSON bodies. You should also know what HTTP methods, status codes, and headers are, and how to open the browser's network panel. Here you will learn why a request that works in curl can fail in the browser, what the server has to send back to allow it, and how the mode and credentials options change what fetch does.
The same-origin policy
An origin is the combination of scheme, host, and port of a URL. Two URLs have the same origin only when all three match.
| URL compared to `https://app.example.com` | Same origin? | Reason |
|---|---|---|
| `https://app.example.com/users` | 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 |
The browser's same-origin policy lets a page send requests to other origins, but by default it does not let the page's JavaScript read the responses. The rule exists because the browser attaches the user's cookies to requests. Without the policy, any site you visited could read your bank's pages using your logged-in session.
CORS (Cross-Origin Resource Sharing) is how a server opts out of that restriction for specific origins. The server sends response headers that say which origins can read the response. The browser enforces those headers. The server does not.
Simple requests and preflight requests
The browser sorts cross-origin requests into two groups.
A simple request goes straight to the server. The browser adds an Origin header and checks the response for Access-Control-Allow-Origin. A request counts as simple only when all of these are true:
- The method is
GET,HEAD, orPOST. - You set only CORS-safelisted request headers, such as
Accept,Accept-Language,Content-Language, andContent-Type. Content-Type, if present, istext/plain,multipart/form-data, orapplication/x-www-form-urlencoded.- No upload progress listeners and no
ReadableStreamrequest body are involved.
Anything else gets a preflight request first. A preflight is an automatic OPTIONS request that asks the server whether the real request is allowed. Sending JSON with Content-Type: application/json triggers a preflight. So does adding an Authorization header or using PUT or DELETE. In practice, most API calls from a front end are preflighted.
If the preflight response lacks the right headers, the browser never sends the real request. Your fetch Promise rejects instead.
The preflight carries two request headers you will see in the network panel: Access-Control-Request-Method names the real method, and Access-Control-Request-Headers lists the non-safelisted headers you set, in lowercase. The server answers with these headers:
| Response header | Purpose |
|---|---|
| `Access-Control-Allow-Origin` | The origin allowed to read the response, or `*` |
| `Access-Control-Allow-Methods` | Methods allowed for the real request |
| `Access-Control-Allow-Headers` | Request headers allowed for the real request |
| `Access-Control-Allow-Credentials` | `true` if cookies and credentials may be used |
| `Access-Control-Max-Age` | Seconds the browser may cache this preflight result |
| `Access-Control-Expose-Headers` | Response headers your JavaScript may read (sent on the real response) |
How CORS failures look in JavaScript
A CORS failure rejects the fetch Promise with a TypeError, the same error type as a network failure. The message depends on the browser ("Failed to fetch" in Chrome, "NetworkError when attempting to fetch resource" in Firefox). On purpose, your code cannot learn the reason. If it could, a hostile page could use that to probe private networks.
try {
const response = await fetch('https://api.example.com/data');
console.log(response.status);
} catch (err) {
// A CORS block and a dropped connection both land here as a TypeError.
console.error(err.name, err.message);
}The details show up only in the developer tools console, with a message like "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present". When you see a TypeError from fetch in development, check the console and the network panel first. The panel shows the OPTIONS request and its response headers.
Request modes
The mode option tells fetch which cross-origin behavior you expect.
| `mode` | Behavior |
|---|---|
| `'cors'` (default) | Cross-origin requests use the CORS protocol. The response is readable if the server allows it. |
| `'same-origin'` | Any cross-origin request rejects at once with a `TypeError`. Useful as a guard. |
| `'no-cors'` | The request is sent with no preflight, and the response is **opaque**. |
An opaque response has type set to 'opaque', status of 0, ok of false, empty headers, and a body you cannot read. no-cors also limits you to GET, HEAD, and POST with safelisted headers. It is meant for cases like a service worker caching third-party images. It does not get around CORS.
const response = await fetch('https://other-site.example/data.json', {
mode: 'no-cors'
});
console.log(response.type); // 'opaque'
console.log(response.status); // 0
console.log(response.ok); // false
const text = await response.text();
console.log(text); // '' : the body is hidden from youThe type property is also worth checking on normal responses: 'basic' means same-origin, 'cors' means a readable cross-origin response, and 'opaque' means no-cors.
The credentials option
Credentials here means cookies, HTTP authentication, and TLS client certificates. The credentials option controls whether the browser sends them and whether it stores cookies set by the response.
| `credentials` | Same-origin requests | Cross-origin requests |
|---|---|---|
| `'same-origin'` (default) | Sent | Not sent; `Set-Cookie` ignored |
| `'include'` | Sent | Sent; `Set-Cookie` stored |
| `'omit'` | Not sent | Not sent |
Credentials are not the same as an Authorization header you set yourself. A bearer token in a header is sent whatever the credentials value is, though it does trigger a preflight.
To send cookies to an API on another origin:
const response = await fetch('https://api.example.com/profile', {
credentials: 'include'
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const profile = await response.json();With credentials: 'include', the server's rules get stricter:
Access-Control-Allow-Credentials: truemust be present, on the preflight and on the real response.Access-Control-Allow-Originmust name the exact origin.*is rejected.Access-Control-Allow-Methods,Access-Control-Allow-Headers, andAccess-Control-Expose-Headerscannot use*as a wildcard. With credentials,*is read as a header literally named*.
Cookies have their own rules
Passing CORS does not guarantee that the cookie gets sent. The cookie's own attributes decide that. A site is the scheme plus registrable domain, so app.example.com and api.example.com are cross-origin but same-site. For cookies sent on cross-site requests:
- The cookie needs
SameSite=None; Secure. Browsers treat a cookie with noSameSiteattribute asSameSite=Lax, which is not sent on cross-sitefetchcalls. Securerequires HTTPS (browsers make an exception forlocalhost).- Many browsers block or partition third-party cookies. A cross-site API cookie may be dropped even when every header is correct. Hosting the API on a subdomain of your app's site keeps the cookies first-party.
A server that allows credentialed requests
This Node.js server shows the headers in practice. Save it as server.mjs, run node server.mjs, and call it from a page served on http://localhost:5173.
import http from 'node:http';
const ALLOWED_ORIGINS = new Set(['http://localhost:5173']);
const server = http.createServer((req, res) => {
const origin = req.headers.origin;
if (origin && ALLOWED_ORIGINS.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
}
// The response changes with Origin, so caches must key on it.
res.setHeader('Vary', 'Origin');
if (req.method === 'OPTIONS') {
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', '600');
res.writeHead(204);
res.end();
return;
}
res.setHeader('Content-Type', 'application/json');
res.setHeader('X-Request-Id', 'req-42');
res.setHeader('Access-Control-Expose-Headers', 'X-Request-Id');
res.setHeader('Set-Cookie', 'session=abc123; Path=/; HttpOnly; SameSite=Lax');
res.writeHead(200);
res.end(JSON.stringify({ receivedCookie: req.headers.cookie ?? null }));
});
server.listen(3000, () => console.log('API on http://localhost:3000'));localhost:5173 and localhost:3000 are different origins but the same site, so SameSite=Lax is enough here. On the client:
const response = await fetch('http://localhost:3000/profile', {
method: 'PUT',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'Ada' })
});
console.log(response.type); // 'cors'
console.log(response.headers.get('X-Request-Id')); // 'req-42' because it is exposed
console.log(await response.json()); // cookie appears on the second callA few details in the server code matter:
- The server echoes the request's
Originonly when it is on an allowlist. Echoing any origin together withAllow-Credentials: truelets every site on the web read your users' data. Vary: Originstops a shared cache from serving one origin's allowed response to another origin.- Without
Access-Control-Expose-Headers,response.headers.get('X-Request-Id')returnsnull. Cross-origin JavaScript sees only the safelisted response headers:Cache-Control,Content-Language,Content-Length,Content-Type,Expires,Last-Modified, andPragma.
Common errors and how to fix them
| Symptom in the console | Cause | Fix |
|---|---|---|
| No `Access-Control-Allow-Origin` header | Server sends no CORS headers, or sends them only on success | Add headers to every response, including errors and `OPTIONS` |
| Wildcard `*` not allowed with credentials | `credentials: 'include'` with `Allow-Origin: *` | Echo the specific allowed origin |
| Request header not allowed by `Access-Control-Allow-Headers` | Preflight does not list a header you set, for example `Authorization` | Add it to `Allow-Headers` |
| Preflight response is not successful | `OPTIONS` route returns 404, 401, or a redirect | Answer `OPTIONS` with 2xx before auth checks |
| Request works but `headers.get()` returns `null` | Header not exposed | Add it to `Access-Control-Expose-Headers` |
| Cookie never arrives | Missing `credentials: 'include'`, wrong `SameSite`, or third-party cookie blocking | Check the cookie attributes in the Application panel |
Exercise
A page on https://shop.example.com calls fetch('https://api.example.com/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }). The server answers POST /cart with Access-Control-Allow-Origin: https://shop.example.com but returns 404 for OPTIONS /cart. What happens, and why?
Show answer
The fetch Promise rejects with a TypeError. Content-Type: application/json is not a safelisted value, so the browser sends an OPTIONS preflight first. The preflight fails with a 404 and no CORS headers, so the browser never sends the POST. The server must answer OPTIONS /cart with a 2xx status, Access-Control-Allow-Origin, Access-Control-Allow-Methods including POST, and Access-Control-Allow-Headers including Content-Type.
Exercise
You add credentials: 'include' to a request that previously worked, and it now fails. The server sends Access-Control-Allow-Origin: * and nothing else. Which two changes does the server need?
Show answer
It must replace * with the exact requesting origin, for example https://app.example.com, and it must add Access-Control-Allow-Credentials: true. Both are needed on the preflight response, if there is one, and on the real response. It should also send Vary: Origin if it chooses the origin value per request.
Exercise
A teammate fixes a CORS error by adding mode: 'no-cors'. The console error goes away, but response.json() throws. Explain what they received.
Show answer
They received an opaque response: type 'opaque', status 0, ok false, no readable headers, and an empty body. That is why parsing JSON fails. no-cors does not bypass CORS. It only allows a request whose response JavaScript cannot read. The fix is to configure CORS on the server or route the call through a same-origin proxy.
Exercise
Your cross-origin response includes the header X-RateLimit-Remaining, and the network panel shows it, but response.headers.get('X-RateLimit-Remaining') returns null. Why?
Show answer
Cross-origin JavaScript can read only the CORS-safelisted response headers unless the server lists others in Access-Control-Expose-Headers. The server must send Access-Control-Expose-Headers: X-RateLimit-Remaining on the real response.