Why only the browser gives you a CORS error, and why a call through your own server doesn't

2025/08/02
securitycorsnextjswebcsrf

You wire up an API call. Postman returns 200. curl returns 200. The backend engineer checks the logs and says "works fine on my end." The same call in the browser fails, and Chrome's console shows:

Access to fetch at 'https://api.example.test:8443/none' from origin 'https://app.example.test:8443'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.

So you go back to the backend: "can you add my origin to the CORS headers?" They do. Next week a new endpoint shows the same error, and you have to ask again.

Why does only the browser fail?


Only the browser checks CORS

The same endpoint, which sends no CORS headers, called two ways:

CallerRequest reached the serverCaller got the body
curlyesyes
JavaScript in a page on another origin (Chrome 156, Firefox 159)yesno, fetch throws a TypeError

The server received the request and answered both times. CORS is a rule the browser applies to JavaScript running in a web page. Postman, curl, and your backend calling another backend don't apply it. So "works in Postman, fails in the browser" is not a contradiction: of these clients, only the browser has the rule.


Origin, SOP, and CORS

An origin is scheme + host + port. Two URLs have the same origin only when all three match:

PageRequest toSame origin?
https://app.example.comhttps://app.example.com/apiyes
https://app.example.comhttps://api.example.comno, the host differs
http://localhost:5173http://localhost:8080no, the port differs
http://app.example.comhttps://app.example.comno, the scheme differs

Same-Origin Policy (SOP) is the browser's default: JavaScript in a page cannot read a response from another origin. Nobody has to switch it on. A frontend at app.example.com reading from api.example.com crosses origins, so the read fails by default.

CORS (Cross-Origin Resource Sharing) is how a server lifts that default for the origins it names. The browser adds an Origin header to the request, and the server answers with Access-Control-Allow-Origin:

GET /data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
 
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com

The value matches the page's origin, so the browser hands the response to the JavaScript. Without that header, the browser does not hand it over.

Which requests go straight to the server

A simple request goes out directly. It has to meet all three conditions (Fetch Standard, MDN):

  1. The method is GET, HEAD, or POST.
  2. Your code sets no headers other than Accept, Accept-Language, Content-Language, and Content-Type, each value at most 128 bytes. (The spec also allows a simple Range header.)
  3. If Content-Type is set, it is application/x-www-form-urlencoded, multipart/form-data, or text/plain.

These are roughly the requests an HTML form can send. Headers the browser adds on its own, like Origin, Cookie, and User-Agent, don't count.

Any other request makes the browser send an OPTIONS request first, the preflight, asking the server whether the real request is allowed:

OPTIONS /data HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
 
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: content-type

Requests from a page to an endpoint with no CORS headers (Chrome 156 and Firefox 159 gave the same results):

RequestPreflightServer receivedJavaScript read the response
GETnoGETno
POST, Content-Type: text/plainnoPOSTno
POST, Content-Type: application/jsonyesOPTIONS onlyno
GET with an Authorization headeryesOPTIONS onlyno
PUTyesOPTIONS onlyno

For a simple request, the server has already processed it, and CORS only decides whether the JavaScript can read the response. For a preflighted request, if the server does not approve the preflight, the real request is never sent.


Send the call through your own origin

The error appears because the browser's request goes to a different origin. If the page calls a server on its own origin, and that server calls the API, the browser's request is same-origin. SOP does not apply to same-origin requests, so there is no CORS header to ask the backend for. The call to the API goes from server to server; it does not pass through the browser, so CORS is never checked.

browser  →  https://app.example.com/api/charge     same origin, no preflight
server   →  https://api.payments.com/charge        server to server, no CORS

A same-origin POST with Content-Type: application/json and an Authorization header went out as one request, with no preflight, in both browsers.

In development, Vite's dev server proxy does this:

// vite.config.js
export default {
  server: {
    proxy: {
      '/api': {
        target: 'https://api.payments.com',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ''),
      },
    },
  },
}

The browser calls /api/charge on the dev server's origin, and Vite forwards it to https://api.payments.com/charge. Without rewrite, Vite keeps the path as it is and the request goes to https://api.payments.com/api/charge (measured on Vite 7.3.7). changeOrigin: true sets the Host header to the target's host.

server.proxy is part of the dev server, so it is gone in production. In production a real server has to be in the path. In the Next.js App Router (13.2 and later), that can be a Route Handler:

// app/api/charge/route.ts
export async function POST(req: Request) {
  const body = await req.json()
  const upstream = await fetch('https://api.payments.com/charge', {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.PAYMENTS_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  })
  return Response.json(await upstream.json())
}

The browser calls /api/charge on its own origin, and your server calls the payment API.

Besides Route Handlers, the fetch in a Server Action ("use server") or a Server Component also runs on the server. With one page for each on Next.js 16.4.3, the browser only sent requests to the Next.js server that served the page, and that server called the payment API:

Route Handler     browser fetch('/api/charge')                     →  Next.js server            →  payment API
Server Action     browser POSTs the current page (Next-Action header)  →  Next.js server            →  payment API
Server Component  browser GETs the page                            →  Next.js server, at render  →  payment API

The same setup keeps the API key out of the browser

In the Route Handler, the line Authorization: Bearer ${process.env.PAYMENTS_KEY} runs on the server. According to the Next.js docs, Next.js puts an environment variable into the browser's JavaScript only when its name starts with NEXT_PUBLIC_; PAYMENTS_KEY is available only on the server. The Route Handler, Server Action, and Server Component pages each used the key only to call the payment API, and the key appeared in none of the requests the browser sent and none of the responses it received.

If the component had called the payment API directly, the key would be in the request the browser makes, in plain text in the DevTools Network tab for anyone who opens it. Routed through your server, the browser's request carries no key. The server adds the key on the server-to-server request, which the user never sees.

Even without an attacker, a key in the browser has already been handed to whoever uses the page: anything the browser sends shows up in DevTools, and any script running in the page can reach whatever your JavaScript can reach. Obscuring or "encrypting" the key on the client doesn't help, because the code that decrypts it ships to the browser too.

If a 'use client' component reads process.env.PAYMENTS_KEY, the browser's JavaScript gets undefined, but when Next.js renders that component on the server, it gets the real value. A test page rendered the variable, and the key ended up in the HTML (Next.js 16.4.3, next dev).

Server Components work the same way. When a test page wrote the key into JSX, or passed it as a prop to a 'use client' component, the key was in the HTML sent to the browser. When the page used the key only to call the payment API and passed the API's result as a prop to the same 'use client' component, the HTML had no key (Next.js 16.4.3, next dev).

Route Handlers, Server Actions, and Server Components can all read the key, as long as they don't render it and don't pass it as a prop to a 'use client' component.

After this change, /api/charge is an endpoint anyone can call, including your own users with DevTools open, so your server has to authenticate the user and rate-limit the route.


When routing through your origin isn't the answer

All of the above is about calling someone else's API. Two other situations work differently.

You own an API that browsers on other origins have to call. If your public API is meant to be called from other people's web apps, it can't go through your server. Set CORS on purpose and list specific origins. When the request carries cookies, the browser rejects Access-Control-Allow-Origin: * anyway (see the reference table below).

The request comes from an attacker. For a simple request, CORS only decides who can read the response, so it does not stop a forged request (CSRF) from reaching your server. The two stories below show what it stops and what it doesn't.

Deeper: how CORS plays out against an attacker (two stories)

Measured in Chrome 156 and Firefox 159. Why a localhost cookie never reaches thembase.localhost covers SameSite in detail: it is a cookie attribute that limits which cookies go along on requests started by another site. In the test, the bank sets three cookies, whose SameSite is unset, Lax, and None; Secure.

Story 1: classic CSRF, where CORS plays no part. A user is logged in to bank.com and opens evil.com, whose page auto-submits a form:

<form action="https://bank.com/transfer" method="POST">
  <input name="to" value="evil-account">
  <input name="amount" value="1000">
</form>
<script>document.forms[0].submit()</script>

A form POST is a simple request, so there is no preflight. It goes straight to bank.com/transfer. Both browsers attached the SameSite=None cookie and the cookie without SameSite, and neither sent the SameSite=Lax cookie. As Why a localhost cookie never reaches thembase.localhost explains, Chrome sends the cookie without SameSite only under a timing condition. If the session cookie goes along, the bank sees a logged-in user asking for a transfer and, with no other defense, carries it out. The bank's CORS settings play no part here; the defenses against this attack are the SameSite=Lax cookies, CSRF token, and Origin check covered in XSS and CSRF: which defense stops which attack.

Story 2: CSRF with fetch, where CORS helps part way. evil.com sends the POST with fetch, credentials: 'include' (which makes a cross-origin request carry cookies), and Content-Type: application/json, so a preflight goes first.

SituationResult (measured in Chrome 156)
The bank sends no CORS headersthe bank receives only the OPTIONS
The bank's preflight approves any origin, but the actual response has no CORS headersthe POST arrives with the SameSite=None cookie; evil.com's JavaScript can't read the result
The same JSON body sent as Content-Type: text/plain with mode: 'no-cors'no preflight; the POST arrives with the SameSite=None cookie

In the first row, CORS did stop the request. But if the bank parses the body as JSON without checking Content-Type, the attacker only has to drop the header as in the last row, and is back to story 1.

Reference: CORS headers (sent by the browser and by the server)

The browser fills in these headers itself; you don't write them in your fetch.

HeaderWhat it carries
OriginThe calling page's scheme + host + port
Access-Control-Request-MethodPreflight only. The method the real request will use.
Access-Control-Request-HeadersPreflight only. The headers the real request will set that are not on the simple list.

You write the server headers in your CORS middleware.

HeaderWhat it controls
Access-Control-Allow-OriginThe allowed origin: one origin that matches Origin, or * for any. With credentials: 'include', * fails.
Access-Control-Allow-MethodsMethods the server accepts from a preflighted request.
Access-Control-Allow-HeadersHeaders outside the simple list that the server accepts.
Access-Control-Allow-CredentialsWith true, JavaScript may read the response to a request sent with credentials: 'include'. On a preflight, without it the real request is not sent.

To send cookies on a cross-origin call, the client opts in with fetch(url, { credentials: 'include' }) or the older xhr.withCredentials = true.


API keys, read access, and CSRF: what handles each

JobWhat does itWhat it stops
Keep secrets out of the clientRoute the call through your own serverYour API key showing up in the browser
Control who can read your responsesSOP by default, CORS to open it upJavaScript on other origins reading sensitive responses
Block forged cross-site requestsSameSite cookie + CSRF token + Origin checkClassic CSRF on simple requests

If you are the one calling an API, route the call through your own origin. You skip the CORS setup and keep the key on the server at the same time. Configure CORS only when you own an endpoint that really has to be read from other origins. Don't count CORS as a CSRF defense, because a simple request reaches your server either way.

XSS and CSRF: which defense stops which attack covers the CSRF side in full.


Environment

ItemVersion
SystemmacOS 15.6 (arm64), Node.js 22.22.3
BrowsersChrome for Testing 156.0.8078.73, Firefox 159.0, headless, driven by puppeteer-core 25.16.0
curl8.7.1
Vite7.3.7
Next.js16.4.3 (next dev, Turbopack), React 19.3.1
Results fromthe server's log of every request it received, and what the page's JavaScript got back

References