Skip to content

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)
  1. The myth and the reality
  2. What CORS actually does in the browser
  3. Why curl and servers ignore it
  4. How to protect your API: authentication, per-user authorization and rate limiting
  5. How to configure CORS correctly
  6. Common mistakes
  7. Frequently asked questions
  8. Checklist

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 assumeWhat actually happens
CORS blocks requests from other sitesMany 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 APIcurl, Postman, scripts and servers call the API with no CORS restriction at all
CORS protects my customers' dataRequiring 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 nothingIn 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, HEAD or POST, no custom headers beyond the safelisted ones, and a form-style Content-Type (application/x-www-form-urlencoded, multipart/form-data or text/plain). The browser sends it straight away. If the response lacks a matching Access-Control-Allow-Origin, the page cannot read it, but the server has already received and processed it.
  • Preflighted request. Everything else: an Authorization header, Content-Type: application/json, a PUT or a DELETE. The browser first sends an OPTIONS request with Access-Control-Request-Method and Access-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 serverWhat the page got
POST /api/subscribe as a formThe POST; the server stored the emailTypeError: Failed to fetch
GET /api/orders/1001 without a tokenThe GET; it answered 401TypeError: Failed to fetch
GET /api/orders/1001 with AuthorizationOnly the OPTIONS; the GET never arrivedTypeError: 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.

the same request, two clientsbrowserpage on another originGET /api/orders/1001200 · no Allow-Originread blockedfetch(): TypeErrorcurlno browserGET + fake Origin200 · the full ordersends any Origin it likesAPI127.0.0.1:8787answers 200to boththe server answered bothonly the browser checks the CORS headers before the page can read

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}
  1. The first line of each block is the command: -s hides the progress bar and -i prints the response headers.
  2. HTTP/1.1 200 OK both times: the server answered the same way.
  3. The second response has no Access-Control-Allow-Origin, because https://otra-tienda.example is not on the list. curl does not care.
  4. The last line is the full order. We left out the Date, Connection, Keep-Alive and Transfer-Encoding headers, 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.

what a request crosses before it reaches the dataany client: browser, curl, scriptrate limitrateLimited()else 429authenticationauthenticate()else 401authorizationorder.userIdelse 404datathe order200CORSnot a layer: it only tells the browserwhich pages on other origins may read the responseall three layers run on the serverthey apply the same to a browser, curl or any other client

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;
}
  1. TOKENS maps each token to a user. In the demo it is an in-memory Map; in your app this is where you verify the session or the signed token with your auth library.
  2. authenticate reads the Authorization header and splits it into scheme and token.
  3. If the scheme is Bearer and 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" });
  1. No user, 401, and nothing else happens.
  2. The regular expression pulls the id out of the URL: /api/orders/1001 gives 1001.
  3. order.userId !== userId is the authorization check: the order exists, but it is not yours.
  4. 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();
  1. WINDOW_MS and MAX_REQUESTS: 5 requests per minute per client (illustrative values; tune them to your traffic).
  2. hits stores, per key, when the window started and how many requests it has seen.
  3. No entry, or an expired window, starts a fresh one at 1.
  4. Otherwise it adds 1 and returns true once the count goes over the limit.
  5. The setInterval drops expired windows every minute so the Map does 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" });
  }
  1. 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.
  2. Over the limit, it answers 429 with Retry-After in 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");
  }
}
  1. ALLOWED_ORIGINS is an exact list read from an environment variable, for example ALLOWED_ORIGINS=https://tienda.example.
  2. Vary: Origin is always sent: the response depends on the origin, and this way no cache serves one origin's response to another.
  3. No Origin, or one not on the list, gets no headers. That is not a block; the browser simply gets no permission.
  4. An allowed origin is echoed back exactly in Access-Control-Allow-Origin; never *, and never whatever arrives unchecked.
  5. Only the preflight (OPTIONS) declares the methods, the allowed headers and Access-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();
  1. The first line logs method, path and origin; that log is where the server column in the table above comes from.
  2. 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.
  3. OPTIONS gets 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
the 204 preflight response, annotatedVary: Originthe answer depends on the origin: keeps caches from mixing themAccess-Control-Allow-Origin: https://tienda.exampleone exact origin from your list; never * with cookies, never nullAccess-Control-Allow-Methods: GET, POSTonly the methods your frontend usesAccess-Control-Allow-Headers: Authorization, Content-Typethe headers the browser may sendAccess-Control-Max-Age: 600seconds the browser may cache this answerwithout them the browser will not let the page readcurl and servers ignore them: the API is protected in code

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's Origin into Access-Control-Allow-Origin without checking it against a list is the same as allowing every origin. Add Access-Control-Allow-Credentials: true and any page could read data with your user's session.
  • Matching origins with includes or startsWith. "https://shop.example.evil.com".startsWith("https://shop.example") returns true. Use an exact comparison, like the demo's Set.
  • Allowing null. MDN's Access-Control-Allow-Origin reference warns that data:, file: and sandboxed documents have a null origin, 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 POST has 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-Origin comes from an exact list of origins.
  • Vary: Origin is on every response.
  • With cookies: a specific origin and Access-Control-Allow-Credentials: true, never *.
  • You hit the API with curl, with no Origin and 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

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published October 30, 2026 · updated November 1, 2026

← Blog