CORS
Your frontend runs on https://app.example.com and your API on https://api.example.com. When the frontend calls the API with fetch, the browser blocks the response — unless the API says it's fine. That permission system is CORS: Cross-Origin Resource Sharing.
Origins and the same-origin policy
An origin is scheme + host + port. Browsers only let a page read responses from its own origin, unless the other server opts in with CORS headers:
| Page origin | Request URL | Same origin? |
|---|---|---|
https://shop.dev |
https://shop.dev/api/cart |
yes |
https://shop.dev |
http://shop.dev/api/cart |
no — different scheme |
https://shop.dev |
https://api.shop.dev/cart |
no — different host |
http://localhost:5173 |
http://localhost:3000/api |
no — different port |
Note: CORS is enforced by browsers only.
curl, Postman, Node'sfetchand other servers ignore it entirely. It protects users' browsers, not your API — you still need authentication.
Simple requests vs preflight
For "simple" requests (GET/HEAD/POST with basic headers), the browser sends the request and checks the response's Access-Control-Allow-Origin header. For anything else — PUT, DELETE, a JSON Content-Type, an Authorization header — it first sends a preflight OPTIONS request asking for permission:
OPTIONS /todos/1 ← browser asks first
Origin: https://app.example.com
Access-Control-Request-Method: DELETE
Access-Control-Request-Headers: authorization
204 No Content ← server answers
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600
DELETE /todos/1 ← only now the real request| Response header | Meaning |
|---|---|
Access-Control-Allow-Origin |
which origin may read the response (* or one exact origin) |
Access-Control-Allow-Methods |
methods allowed in preflighted requests |
Access-Control-Allow-Headers |
request headers the client may send |
Access-Control-Allow-Credentials |
true to allow cookies; can't be combined with origin * |
Access-Control-Max-Age |
seconds the browser may cache the preflight result |
Access-Control-Expose-Headers |
response headers JavaScript may read (beyond the basic ones) |
Writing CORS middleware by hand
The cors npm package is what you'd normally use, but the logic fits in a dozen lines. Allow a list of origins, answer preflights directly, and add Vary: Origin so caches don't mix answers for different origins:
const express = require('express');
function cors({ origins, methods = 'GET, POST, PUT, PATCH, DELETE', headers = 'Content-Type, Authorization' }) {
return (req, res, next) => {
const origin = req.get('Origin');
res.vary('Origin');
if (origin && origins.includes(origin)) {
res.set('Access-Control-Allow-Origin', origin);
if (req.method === 'OPTIONS') {
res.set({
'Access-Control-Allow-Methods': methods,
'Access-Control-Allow-Headers': headers,
'Access-Control-Max-Age': '600',
});
return res.sendStatus(204);
}
}
next();
};
}
const app = express();
app.use(cors({ origins: ['https://app.example.com'] }));
app.delete('/todos/:id', (req, res) => res.sendStatus(204));
app.get('/todos', (req, res) => res.json([]));
const server = app.listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
const show = (label, res) =>
console.log(label.padEnd(15), res.status, 'allow-origin =', res.headers.get('access-control-allow-origin'), '| allow-methods =', res.headers.get('access-control-allow-methods'));
show('preflight ok', await fetch(base + '/todos/1', {
method: 'OPTIONS',
headers: { Origin: 'https://app.example.com', 'Access-Control-Request-Method': 'DELETE' },
}));
show('GET ok', await fetch(base + '/todos', { headers: { Origin: 'https://app.example.com' } }));
show('GET evil', await fetch(base + '/todos', { headers: { Origin: 'https://evil.example' } }));
show('no Origin', await fetch(base + '/todos'));
server.close();
});preflight ok 204 allow-origin = https://app.example.com | allow-methods = GET, POST, PUT, PATCH, DELETE
GET ok 200 allow-origin = https://app.example.com | allow-methods = null
GET evil 200 allow-origin = null | allow-methods = null
no Origin 200 allow-origin = null | allow-methods = null
The request from evil.example still got a 200 — the server doesn't block it. But without an Access-Control-Allow-Origin header that matches, the browser refuses to hand the response to the evil page's JavaScript.
Using the cors package
const cors = require('cors');
app.use(cors({
origin: ['https://app.example.com', 'http://localhost:5173'],
credentials: true, // allow cookies
maxAge: 600,
}));Common mistakes
| Mistake | Fix |
|---|---|
Access-Control-Allow-Origin: * together with cookies |
list exact origins and set credentials: true |
| CORS middleware registered after the routes | register it first, so preflights get answered |
reflecting any Origin back without checking |
compare against an allow-list |
| "fixing" a CORS error from server-side code | CORS errors only happen in browsers; check the browser's network tab |
auth middleware rejecting the OPTIONS preflight with 401 |
let preflights through before auth (browsers never send credentials on preflight) |
Tip: During development, a dev-server proxy (e.g. Vite's
server.proxy) makes the frontend and API share one origin, so you don't need CORS at all locally.
Test yourself
Which pair of URLs has the SAME origin?
- http://a.com and https://a.com
- https://a.com/x and https://a.com/y
- https://a.com and https://api.a.com
- http://localhost:3000 and http://localhost:5173
Who enforces CORS?
- Express
- The operating system
- The browser
- The DNS server
Why does a browser send an OPTIONS request before DELETE /todos/1?
- To check the server is online
- It's a CORS preflight asking whether the method and headers are allowed
- To download the resource first
- Because DELETE is not a real HTTP method