Skip to content

CORS: who the browser lets you call

Working knowledgeConcept

Your request works in curl and fails in the browser with a red CORS error, even though the server logged it and answered 200. The browser is not broken: it is following a rule about who may read what. Here is the rule, the extra request it sometimes sends, and the headers that let your page through.

01 The server answered, and you still got an error

A shop front end runs on http://localhost:5173 during development. Its API runs on http://localhost:3000. The page asks the API for the cart:

cart.js
const res = await fetch('http://localhost:3000/api/cart');
console.log(await res.json());

The server log shows the request and a 200. Yet the script throws, and the console shows a CORS error. Run the same request with curl and it works. Both observations are correct: the request reached the server, and the browser then refused to give the answer to your script. CORS (Cross-Origin Resource Sharing) is how a server tells the browser that handing it over is fine.

02 What counts as the same origin

An origin is three things: the scheme, the host and the port. Two URLs share an origin only if all three match. The path does not matter.

Compared with the page at https://shop.example
URLSame origin?Why
https://shop.example/api/cartYesSame scheme, host and port (443 is the default)
https://shop.example:443/cartYesWriting the default port changes nothing
http://shop.example/cartNoDifferent scheme
https://api.shop.example/cartNoDifferent host, even as a subdomain
https://shop.example:8443/cartNoDifferent port

The browser’s same-origin policy says a page may freely send requests anywhere, but may only read responses from its own origin. The reason is cookies. Your browser attaches your bank’s cookies to any request to the bank. Without the rule, a page on any site could fetch your account page with your cookies and read your balance.

So CORS is not a wall around the server. It is a relaxation of a browser rule: the server opts in, response by response, to letting another origin read it.

03 A simple request: sent first, checked after

Some requests are simple: the method is GET, HEAD or POST, and the only headers the script sets are safelisted ones such as Accept or Content-Type with text/plain, multipart/form-data or application/x-www-form-urlencoded. A plain HTML form could always send these, so the browser sends them straight away and checks the answer afterwards.

A simple GET with no CORS headers
Step 1 of 5
localhost:5173 calls localhost:3000
Page scriptBrowserAPI :3000Nothing sent yet
  • just sent
  • sent earlier
  • blocked by the browser

The page runs at http://localhost:5173 and the API at http://localhost:3000. The ports differ, so they are two origins. Nothing has been sent yet.

For a simple request, the server has already done the work by the time the browser blocks the response. CORS stops the page reading the result; it does not stop a POST from changing data. Protect state-changing endpoints with authentication and CSRF defences, not with CORS.

04 Preflight: asking before sending

Anything outside the simple set could not have been sent by an old-style form, so a server written before CORS might not expect it. For those, the browser first asks permission with an OPTIONS request called a preflight. Common triggers: PUT, PATCH and DELETE, a JSON Content-Type, and custom headers such as Authorization or X-Request-Id.

save-cart.js
await fetch('http://localhost:3000/api/cart', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items: 3 }),
});
A PUT with JSON: preflight, then the request
Step 1 of 8
localhost:5173 calls localhost:3000
Page scriptBrowserAPI :3000Nothing sent yet
Browser’s preflight cache
Empty
  • just sent or stored
  • earlier
  • handed to the script

The script wants to save the cart with PUT and a JSON body. Nothing is sent yet and the preflight cache is empty.

Access-Control-Max-Age is capped by the browser: Chrome keeps a preflight for at most two hours and Firefox for at most 24 hours. Without the header the answer is kept for only five seconds, so almost every call pays for two round trips.

05 The headers that allow it

The browser writes the request headers; your server writes the response headers. Every one of these is about what the browser allows the page to do.

CORS headers and who sends them
HeaderSent byMeaning
OriginBrowserThe origin of the page making the request
Access-Control-Request-MethodBrowser (preflight)The method the real request will use
Access-Control-Request-HeadersBrowser (preflight)Non-safelisted headers the real request will carry
Access-Control-Allow-OriginServerThe one origin allowed to read, or * for any
Access-Control-Allow-MethodsServer (preflight)Methods allowed beyond the simple ones
Access-Control-Allow-HeadersServer (preflight)Request headers the page may send
Access-Control-Allow-CredentialsServertrue lets the page send and read with cookies
Access-Control-Expose-HeadersServerResponse headers the script may read, beyond the basic ones
Access-Control-Max-AgeServer (preflight)Seconds the browser may reuse this preflight

Here is a small Node server that answers both the preflight and the real request, allowing only the dev front end:

server.js
const http = require('node:http');
const ALLOWED = 'http://localhost:5173';
http.createServer((req, res) => {
if (req.url !== '/api/cart') return res.writeHead(404).end();
// The answer depends on Origin, so caches must key on it.
res.setHeader('Vary', 'Origin');
if (req.headers.origin === ALLOWED) {
res.setHeader('Access-Control-Allow-Origin', ALLOWED);
}
if (req.method === 'OPTIONS') { // the preflight
res.writeHead(204, {
'Access-Control-Allow-Methods': 'GET, PUT',

You can play the browser’s part with curl and see the server’s side of the deal. This is a real run of the same code listening on port 3917, with the Date and connection headers trimmed:

Shell
curl -si -X OPTIONS localhost:3917/api/cart \
-H 'Origin: http://localhost:5173' \
-H 'Access-Control-Request-Method: PUT' \
-H 'Access-Control-Request-Headers: content-type'
HTTP
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin
Access-Control-Allow-Methods: GET, PUT
Access-Control-Allow-Headers: Content-Type
Access-Control-Max-Age: 600

Send the same GET with -H 'Origin: http://evil.example' and the server returns the cart with no Access-Control-Allow-Origin header. curl prints the body anyway, because curl does not enforce CORS. Only browsers do.

06 Cookies across origins

By default a cross-origin fetch sends no cookies. To send them you opt in on both sides: the script passes credentials: 'include', and the server answers with Access-Control-Allow-Credentials: true. The browser then also refuses *: Access-Control-Allow-Origin must name the exact origin.

Rejected with cookies
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Accepted
Access-Control-Allow-Origin: https://shop.example
Access-Control-Allow-Credentials: true
Vary: Origin

When the server picks the allowed origin from a list and echoes it back, the response differs per origin. Vary: Origin tells shared caches and CDNs to store a separate copy per origin, so one site never gets a response labelled for another.

Never echo whatever Origin arrives together with Access-Control-Allow-Credentials: true. That lets every site on the internet read your users’ data with their cookies, which is exactly what the same-origin policy exists to stop. Compare against a fixed list.

Cookies have their own rule on top. Cross-site is a looser test than cross-origin: api.shop.example and shop.example are different origins but the same site, so SameSite=Lax cookies still flow. A truly different site, such as shop-api.com, needs the cookie set with SameSite=None; Secure, and some browsers block such third-party cookies by default.

07 When CORS bites

app.use(requireLogin); // runs before CORSAuth rejects the preflightThe preflight carries no cookies or Authorization header, so an auth check that runs first answers 401, the preflight fails, and the real request is never sent. Answer OPTIONS before authentication.
500 Internal Server Error (no CORS headers)A server error that looks like CORSIf your error handler sends the response without the CORS headers, the browser reports a CORS error and hides the 500. Check the Network panel or the server log for the real status.
fetch(url, { mode: 'no-cors' })no-cors does not fix anythingIt sends the request but gives you an opaque response: status 0, no headers, no body. It is meant for things like caching images, not for reading APIs.
Access-Control-Allow-Origin: https://a.example, https://b.exampleA list of originsThe header holds one origin or *, never a list. To allow several, check Origin against your list on the server and echo the match, with Vary: Origin.
OPTIONS /api/cart → 301 /api/cart/A redirected preflightBrowsers do not follow redirects on a preflight, so a trailing-slash redirect fails it. Call the final URL directly.
Access-Control-Allow-Origin: *Treating CORS as access controlCORS only governs browsers. curl, scripts and other servers ignore it, so an API still needs real authentication.

08 Check yourself

Question

A page on https://app.example sends POST /api/orders with Content-Type: text/plain to https://api.example. The response has no CORS headers. What happened?

Question

Which of these requests from https://shop.example triggers a preflight?

Question

The server sends Access-Control-Allow-Origin: * and the script uses credentials: 'include'. What does the script get?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?