Does CORS protect your API? What it does and what actually protects it
Guide/ 13 min read
An API with strict CORS still answers curl and any server. We tested it locally and built what protects it: authentication, per-user authorization and rate limits.
- Node.js
- Security
In this article (8)
No, CORS does not protect your API. It is a browser rule that decides whether JavaScript on a page from another origin may read your server's response. curl, scripts and other servers ignore it and get the response anyway. What protects an API is authentication, per-user authorization and rate limiting, all enforced on the server.
This article tests that with a local Node server, from curl and from Chromium: what reaches the server and what the page can read. Then it builds the three layers that do protect the API, with no dependencies, and a correct CORS setup. If your frontend is Next.js, also check which NEXT_PUBLIC variables end up in the browser, and if your API takes payments, how an idempotency key prevents double charges.
The myth and the reality
The myth goes like this: "I locked CORS down to my domain, so nobody else can call my API." It is an easy mistake to make. A CORS error is the first thing you hit when your frontend cannot talk to your backend, and it feels like a wall.
The reality, per MDN's CORS guide: CORS is an HTTP-header based mechanism that lets a server tell the browser which other origins it should allow to load its resources. The browser is the one that obeys. And what it blocks, in many cases, is not the request but reading the response.
| What people assume | What actually happens |
|---|---|
| CORS blocks requests from other sites | Many requests reach the server and run; the browser only stops the page from reading the response |
| With CORS, nobody outside my domain can call the API | curl, Postman, scripts and servers call the API with no CORS restriction at all |
| CORS protects my customers' data | Requiring a session, and checking that every resource belongs to the user asking for it, is what protects it |
| If there was a CORS error, the request did nothing | In our test, a blocked form POST ran anyway: the server stored the data |
CORS does have a job: it relaxes, in a controlled way, the browser's same-origin policy, which stops another page from reading your site's data with your user's session. It protects the user inside their browser. It is not access control for your server.
What CORS actually does in the browser
Two URLs share an origin when the protocol, host and port all match. https://shop.example and https://api.shop.example are different origins, and so are http://localhost:5173 and http://localhost:5174. MDN sums up the default: cross-origin writes (links, redirects, form submissions) are typically allowed, and cross-origin reads are typically disallowed.
When a page's JavaScript calls another origin with fetch(), the browser adds an Origin header and takes one of two paths:
- Simple request.
GET,HEADorPOST, no custom headers beyond the safelisted ones, and a form-styleContent-Type(application/x-www-form-urlencoded,multipart/form-dataortext/plain). The browser sends it straight away. If the response lacks a matchingAccess-Control-Allow-Origin, the page cannot read it, but the server has already received and processed it. - Preflighted request. Everything else: an
Authorizationheader,Content-Type: application/json, aPUTor aDELETE. The browser first sends anOPTIONSrequest withAccess-Control-Request-MethodandAccess-Control-Request-Headers. If the answer does not allow it, the real request is never sent.
We tested this in Chromium 151 with Playwright. The API runs on http://127.0.0.1:8787 and only allows the origin http://localhost:5173. We made the same three calls from a page on that origin and from one on http://localhost:5174. The server column comes from the API's own log:
| Call from localhost:5174 (not allowed) | What reached the server | What the page got |
|---|---|---|
POST /api/subscribe as a form | The POST; the server stored the email | TypeError: Failed to fetch |
GET /api/orders/1001 without a token | The GET; it answered 401 | TypeError: Failed to fetch |
GET /api/orders/1001 with Authorization | Only the OPTIONS; the GET never arrived | TypeError: Failed to fetch |
From localhost:5173 the page read all three responses (201, 401 and 200), and the third reached the server as an OPTIONS followed by the GET. The row that matters is the first one: the email sent from the blocked origin was stored. The next sign-up from the allowed origin returned {"subscribed":3}, not 2.
Look at what the page saw, too: a bare TypeError. MDN explains why: for security reasons, JavaScript does not get the details of a CORS failure, only the console does. In Chromium the console said No 'Access-Control-Allow-Origin' header is present on the requested resource.
Why curl and servers ignore it
CORS exists to protect the user inside their browser, so that a page they opened cannot read another site's data with their cookies. curl has no page, no user and no third-party session to protect, so it applies no rule at all. It can also send any Origin header it likes. The same goes for a Python script, Postman or somebody else's backend.
Scroll the figure sideways to see all of it
Same API, first with no Origin header:
$ curl -si http://127.0.0.1:8787/api/orders/1001 -H "Authorization: Bearer tok_ana"
HTTP/1.1 200 OK
Vary: Origin
Content-Type: application/json
{"id":"1001","userId":"ana","total":1250}
And now pretending to be an origin the API does not allow:
$ curl -si http://127.0.0.1:8787/api/orders/1001 -H "Authorization: Bearer tok_ana" -H "Origin: https://otra-tienda.example"
HTTP/1.1 200 OK
Vary: Origin
Content-Type: application/json
{"id":"1001","userId":"ana","total":1250}
- The first line of each block is the command:
-shides the progress bar and-iprints the response headers. HTTP/1.1 200 OKboth times: the server answered the same way.- The second response has no
Access-Control-Allow-Origin, becausehttps://otra-tienda.exampleis not on the list. curl does not care. - The last line is the full order. We left out the
Date,Connection,Keep-AliveandTransfer-Encodingheaders, which change nothing here.
The only thing protecting that order is that the command carried a valid token. Without one, the answer would have been a 401. That is where the real protection lives.
How to protect your API: authentication, per-user authorization and rate limiting
A public API on the internet gets requests from any client. Each request has to clear three checks on the server: who are you (authentication), may you touch this (authorization), and how many times have you tried (rate limiting). Because they run on the server, they apply equally to a browser, to curl and to anything else.
Scroll the figure sideways to see all of it
1. Authentication
const TOKENS = new Map([
["tok_ana", "ana"],
["tok_beto", "beto"],
]);
function authenticate(req) {
const [scheme, token] = (req.headers.authorization ?? "").split(" ");
return scheme === "Bearer" ? (TOKENS.get(token) ?? null) : null;
}
TOKENSmaps each token to a user. In the demo it is an in-memoryMap; in your app this is where you verify the session or the signed token with your auth library.authenticatereads theAuthorizationheader and splits it into scheme and token.- If the scheme is
Bearerand the token exists, it returns the user id; otherwise,null.
2. Per-user authorization
Being logged in is not enough. The most expensive bug in a store's API is handing order 1002 to anyone who requests /api/orders/1002 just because they have a session. Every resource is checked against the user asking for it:
if (!userId) return send(res, 401, { error: "unauthenticated" });
const match = req.url.match(/^\/api\/orders\/(\w+)$/);
if (req.method === "GET" && match) {
const order = ORDERS.get(match[1]);
if (!order || order.userId !== userId) return send(res, 404, { error: "not_found" });
return send(res, 200, order);
}
send(res, 404, { error: "not_found" });
- No user, 401, and nothing else happens.
- The regular expression pulls the id out of the URL:
/api/orders/1001gives1001. order.userId !== userIdis the authorization check: the order exists, but it is not yours.- Both cases (missing or not yours) return 404, so the API does not confirm which ids exist. A 403 is fine too; what matters is not returning the data.
With beto's token asking for ana's order:
$ curl -si http://127.0.0.1:8787/api/orders/1001 -H "Authorization: Bearer tok_beto"
HTTP/1.1 404 Not Found
{"error":"not_found"}
3. Rate limiting
const WINDOW_MS = 60_000;
const MAX_REQUESTS = 5;
const hits = new Map();
function rateLimited(key) {
const now = Date.now();
const entry = hits.get(key);
if (!entry || now - entry.start >= WINDOW_MS) {
hits.set(key, { start: now, count: 1 });
return false;
}
entry.count += 1;
return entry.count > MAX_REQUESTS;
}
setInterval(() => {
const now = Date.now();
for (const [key, entry] of hits) if (now - entry.start >= WINDOW_MS) hits.delete(key);
}, WINDOW_MS).unref();
WINDOW_MSandMAX_REQUESTS: 5 requests per minute per client (illustrative values; tune them to your traffic).hitsstores, per key, when the window started and how many requests it has seen.- No entry, or an expired window, starts a fresh one at 1.
- Otherwise it adds 1 and returns
trueonce the count goes over the limit. - The
setIntervaldrops expired windows every minute so theMapdoes not grow forever;unref()keeps that timer from holding the process open.
This is how the handler uses it, right at the top:
const userId = authenticate(req);
if (rateLimited(userId ?? req.socket.remoteAddress)) {
res.setHeader("Retry-After", "60");
return send(res, 429, { error: "too_many_requests" });
}
- The key is the user when there is a token and the IP when there is not, so the limit also slows down anyone guessing tokens.
- Over the limit, it answers 429 with
Retry-Afterin seconds.
$ for i in 1 2 3 4 5 6; do curl -s -o /dev/null -w "%{http_code} " http://127.0.0.1:8787/api/orders/1002 -H "Authorization: Bearer tok_beto"; done
200 200 200 200 200 429
$ curl -si http://127.0.0.1:8787/api/orders/1002 -H "Authorization: Bearer tok_beto" | head -4
HTTP/1.1 429 Too Many Requests
Vary: Origin
Retry-After: 60
This limiter lives in one process's memory. If your API runs on several instances, each one counts on its own, so use a shared store or your platform's rate limiter. And behind a proxy, req.socket.remoteAddress is the proxy's IP, not the client's.
How to configure CORS correctly
You still need CORS when your frontend lives on a different origin from your API, for example https://shop.example calling https://api.shop.example. If they share an origin, like a Next.js app calling its own /api, you need no CORS headers at all. This is the demo's function (the demo store's origin is https://tienda.example, "tienda" being Spanish for shop):
const ALLOWED_ORIGINS = new Set((process.env.ALLOWED_ORIGINS ?? "").split(",").filter(Boolean));
function cors(req, res) {
const origin = req.headers.origin;
res.setHeader("Vary", "Origin");
if (!origin || !ALLOWED_ORIGINS.has(origin)) return;
res.setHeader("Access-Control-Allow-Origin", origin);
if (req.method === "OPTIONS") {
res.setHeader("Access-Control-Allow-Methods", "GET, POST");
res.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
res.setHeader("Access-Control-Max-Age", "600");
}
}
ALLOWED_ORIGINSis an exact list read from an environment variable, for exampleALLOWED_ORIGINS=https://tienda.example.Vary: Originis always sent: the response depends on the origin, and this way no cache serves one origin's response to another.- No
Origin, or one not on the list, gets no headers. That is not a block; the browser simply gets no permission. - An allowed origin is echoed back exactly in
Access-Control-Allow-Origin; never*, and never whatever arrives unchecked. - Only the preflight (
OPTIONS) declares the methods, the allowed headers andAccess-Control-Max-Age: how many seconds the browser may cache that answer.
const server = createServer(async (req, res) => {
console.log(`${req.method} ${req.url} origin=${req.headers.origin ?? "-"}`);
cors(req, res);
if (req.method === "OPTIONS") return res.writeHead(204).end();
- The first line logs method, path and origin; that log is where the server column in the table above comes from.
cors()runs before anything else, so 401, 404 and 429 responses carry the headers too. Add them only to 200 responses and your frontend sees a CORS error when the server actually said 401. In our test, from the allowed origin, the page read the 401 without trouble.OPTIONSgets a bodiless 204 without going through authentication: per MDN, a preflight never carries credentials.
This is the API answering a preflight, seen from curl:
$ curl -si -X OPTIONS http://127.0.0.1:8787/api/orders/1001 -H "Origin: https://tienda.example" -H "Access-Control-Request-Method: GET" -H "Access-Control-Request-Headers: authorization"
HTTP/1.1 204 No Content
Vary: Origin
Access-Control-Allow-Origin: https://tienda.example
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 600
Scroll the figure sideways to see all of it
Cookies and credentials
If your frontend authenticates with cookies instead of a token in Authorization, the fetch call needs credentials: "include" and the API must answer Access-Control-Allow-Credentials: true. Then Access-Control-Allow-Origin has to be a specific origin: per MDN, the * wildcard does not work with credentials. We tested it against an API that answered *. Without credentials the page read the 200; with credentials: "include", Chromium blocked it with this message:
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'.
Common mistakes
- Using CORS as access control. It does not stop curl, scripts or servers, and for simple requests it does not even stop the server from running them.
- Reflecting any
Origin. Copying the request'sOriginintoAccess-Control-Allow-Originwithout checking it against a list is the same as allowing every origin. AddAccess-Control-Allow-Credentials: trueand any page could read data with your user's session. - Matching origins with
includesorstartsWith."https://shop.example.evil.com".startsWith("https://shop.example")returnstrue. Use an exact comparison, like the demo'sSet. - Allowing
null. MDN's Access-Control-Allow-Origin reference warns thatdata:,file:and sandboxed documents have anullorigin, and anyone can create one. - Forgetting
Vary: Origin. With a CDN or cache in front, a response carrying one origin's permission can end up served to another. - Adding CORS headers to successful responses only. The frontend sees a CORS error instead of the real 401 or 429, and debugging takes twice as long.
- Counting on the preflight to guard endpoints that change data. A form
POSThas no preflight. If it changes anything important, require authentication and, with cookies, a CSRF token.
Frequently asked questions
Does CORS protect against CSRF?
Not on its own. A form on another site can send your API a simple POST with no preflight, and in our test the server ran it. To stop cross-origin writes, MDN recommends checking an unguessable token in the request: a CSRF token.
Why does it work in Postman but not in my frontend?
Because Postman is not a browser and does not apply CORS. If the browser shows the error, the response is missing an Access-Control-Allow-Origin with your origin, or the preflight does not allow your method or headers. The browser console tells you which one.
Can I use Access-Control-Allow-Origin: *?
Yes, for public data anyone may read without a session, like a catalog or the stock shown on the storefront. It does not work with cookies or other credentials, and private data does not need it: use the exact list of origins.
How do I set up CORS in Next.js?
In a route handler, by returning the same headers on the Response. The route.js documentation has an example that uses *, and for several handlers it points to next.config.js. If the page and the API share an origin, you do not need CORS. Either way, the API still needs its three layers.
Checklist
- Every private endpoint requires authentication on the server.
- Every resource is checked against the user asking for it.
- There is a rate limit per user and per IP that answers 429.
- Endpoints that change data do not rely on CORS or the preflight.
Access-Control-Allow-Origincomes from an exact list of origins.Vary: Originis on every response.- With cookies: a specific origin and
Access-Control-Allow-Credentials: true, never*. - You hit the API with curl, with no
Originand with a fake one, and it returns nothing without a token.
CORS decides who may read a response inside the browser; your API's security is decided on the server. If you work with Next.js, continue with NEXT_PUBLIC variables and secrets, because CORS does not protect a key that ships in the bundle either. If your API takes payments, read how idempotency keys prevent double charges, and if it decrements stock, how to prevent overselling.
Saw this on Instagram? Comment CORS on the Reel and I'll send you the guide.
Written by

Published October 30, 2026 · updated November 1, 2026