Browser security
The browser keeps each origin to itself. CORS is how a server lets another origin read its answers, and a CSP is how a page limits what it will load or send. Watch requests get sent, held back and let through, then find the CORS setting that leaks your data.
What you'll take away
- Work out whether two URLs share an origin: scheme, host and port must all match
- Explain why a CORS error doesn't mean the request never reached the server
- Answer CORS from an allowlist, never by echoing any Origin back with credentials
- Write a CSP with script-src, connect-src and frame-ancestors, trying Report-Only first
The 1-minute version
Tap a point and the picture below plays that step.
(no Access-Control-* headers)No requests yet
Try evil.example against each API answer and find the one that lets it read your data. Then switch to CSP and try all four with it off and on
https://shop.example calls fetch("https://api.shop.example/me") with a GET, and the API sends no CORS headers at all. What happens?
The picture: your browser is the yard at the front of the city, inside a dashed line, with two tabs standing in it as houses: the shop's page and a page on evil.example (red). Every request leaves the yard by one street, through the browser's own check, a post with a bar across it. Out on the back street stand shop.example's server and its API; evil.example's server is the red building on its own road. Each step is one request or one check: a light goes out (a gold one rides along when cookies go too) and either stops at the check or comes back to the page, and the board in the middle shows the origins compared, the CORS headers the server answers, or the CSP in force. A model of the Fetch standard and CSP, not a real browser.
Compare them all: CORS
Every tile gets the same five requests: three from shop.example, two from evil.example open in another tab. ✓ the page reads it, ✗ it reached the server but the browser won't let the page read it, – the preflight failed so it was never sent, !! the attacker reads your data.
Use it when An API no page on another origin should call: the safest default
Skip it when When your own pages live on another origin than the API (shop vs api.shop): they can read nothing
A model of the Fetch standard, not measured in a browser. It assumes the API's cookie is SameSite=None, as a cross-site API's must be; with Lax the browser wouldn't send it from evil.example at all. Press any tile to see it large above, with when it fits.
Three rules, one enforcer
| Rule | Who sets it | What it does |
|---|---|---|
| same-origin policy | the browser, always | A page can't read another origin's answers, frames or storage |
| CORS | the server with the data | Lets named origins read its answers |
| CSP | the page itself | Limits what the page loads, runs, sends and who frames it |
CORS isn't a firewall
A simple cross-origin request is sent, and the server does the work; the browser only hides the answer from the page. Anything that changes data still needs its own guard: SameSite cookies, a CSRF token, or checking the Origin header on the server.
An allowlist, not a mirror
Answer Access-Control-Allow-Origin with exact origins you know. Copying whatever Origin arrives, with Allow-Credentials, lets any site read your users' data. Add Vary: Origin so a cache never serves one origin's answer to another.
CSP is the second line
A strict script-src stops an injected script from running, and connect-src stops data going out, but the hole that let the script in is still a bug. Escape output first; let the CSP catch what slips through. Start with Content-Security-Policy-Report-Only to see what it would block.
In real code
// An API on another origin with CORS done right: an allowlist (never "echo any Origin"), credentials only for it,
// Vary: Origin, a preflight answer, and the page's own CSP. A real node:http server on 127.0.0.1; the requests below
// carry the Origin header a browser would add. Node doesn't enforce CORS (a browser does), so this checks what the
// server answers: the headers the browser then goes by.
// Run: node cors.ts (Node 23.6+; on Node 22: node --experimental-strip-types cors.ts)
import assert from "node:assert/strict";
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
const ALLOWED = new Set(["https://shop.example"]); // exact origins: scheme + host + port
const CSP = "default-src 'self'; script-src 'self'; connect-src 'self' https://api.shop.example; frame-ancestors 'none'";
const server = createServer((req, res) => {
const origin = req.headers.origin;
res.setHeader("Vary", "Origin"); // the answer depends on Origin: caches must keep them apart
if (origin && ALLOWED.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
if (req.method === "OPTIONS") { // the preflight
if (origin && ALLOWED.has(origin)) {
res.setHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
res.setHeader("Access-Control-Max-Age", "600");
}
res.writeHead(204);
return res.end();
}
if (req.url === "/") { res.writeHead(200, { "content-type": "text/html", "content-security-policy": CSP }); return res.end("<!doctype html><title>shop</title>"); }
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ user: "mai" }));
});
await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const ask = (origin: string, method = "GET", extra: Record<string, string> = {}) => fetch(`${base}/me`, { method, headers: { origin, ...extra } });
const shop = await ask("https://shop.example");
const evil = await ask("https://evil.example");
const pre = await ask("https://shop.example", "OPTIONS", { "access-control-request-method": "PUT", "access-control-request-headers": "content-type" });
const preEvil = await ask("https://evil.example", "OPTIONS", { "access-control-request-method": "PUT" });
const page = await fetch(base + "/");
server.close();
assert.equal(shop.headers.get("access-control-allow-origin"), "https://shop.example");
assert.equal(shop.headers.get("access-control-allow-credentials"), "true");
assert.equal(evil.status, 200); // it was sent and answered...
assert.equal(evil.headers.get("access-control-allow-origin"), null); // ...but a browser won't let evil.example read it
assert.equal(pre.headers.get("access-control-allow-methods"), "GET, PUT, DELETE");
assert.equal(preEvil.headers.get("access-control-allow-methods"), null);
assert.equal(shop.headers.get("vary"), "Origin");
assert.match(page.headers.get("content-security-policy") ?? "", /frame-ancestors 'none'/);
console.log("shop.example: Allow-Origin shop.example + credentials · evil.example: 200 but no Allow-Origin (unreadable in a browser) · preflight PUT: allowed for shop, not for evil · Vary: Origin · CSP on the page");
node cors.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: shop.example: Allow-Origin shop.example + credentials · evil.example: 200 but no Allow-Origin (unreadable in a browser) · preflight PUT: allowed for shop, not for evil · Vary: Origin · CSP on the pageA real node:http API on 127.0.0.1: an allowlist of origins, credentials only for them, Vary: Origin, a preflight answer, and a CSP on the page. Node doesn't enforce CORS, so this checks what the server answers: the headers a browser goes by.
Common questions
Does a CORS error mean the request never reached the server?
Not always. A simple GET is sent and the server does the work; the browser only hides the answer from the page. What isn't sent is the real request after a failed preflight, like a PUT or a JSON body.
Does CORS protect against CSRF?
No. CORS only decides who may read the answer. A form or a simple request from another site still reaches the server and does its work. Anything that changes data needs its own guard: SameSite cookies, a CSRF token, or checking the Origin header on the server.
What is a preflight, and when does it happen?
An OPTIONS request the browser sends first, for a cross-origin request that isn't simple: a PUT or DELETE, a JSON body, a custom header. Only when the server answers with matching Allow-Origin, Allow-Methods and Allow-Headers does the real request follow.
Can't I just answer Access-Control-Allow-Origin: *?
For public data anyone may read, like prices, yes. Not for requests with cookies: the browser refuses * together with credentials. Then you must answer an exact origin, plus Allow-Credentials: true.
What's wrong with echoing back whatever Origin arrives?
The browser trusts what the server says. Echo every origin with credentials and any site your users open can read their private data with their cookie (if it's SameSite=None). Use an allowlist of origins you know, and add Vary: Origin.
How are CORS and CSP different?
CORS: the server with the data tells the browser which origins may read its answers, loosening same-origin. CSP: the page tells the browser what it will load or send, tightening itself. The browser enforces both.
Which CSP directive stops what?
script-src: where scripts may come from; leave out 'unsafe-inline' and injected ones don't run. connect-src: where fetch and WebSocket may go, so data can't leak out. frame-ancestors: who may frame your page, against clickjacking.
How do I add a CSP without breaking my site?
Start with Content-Security-Policy-Report-Only: the browser reports what it would block without blocking it. Watch the reports for a while, fix what trips, then switch to the real header.
Next lesson
Cookies and sessionsLevel: Intermediate
Same-origin and CORS decide what a page may read; next, the cookie flags that decide when your login goes along.