Sub topic 15
Same-origin policy and CORS
This chapter assumes you can read HTTP requests and headers, know how cookies are sent back to a server, and can run a small Node.js script. Earlier chapters covered all of these.
Why browsers restrict cross-origin reads
You are logged in to https://bank.example in one tab. In another tab you open a page from https://evil.example. That page's JavaScript could call fetch("https://bank.example/account"). The browser would attach your bank cookies automatically. Without a rule, the malicious script could read your balance.
The same-origin policy (SOP) is that rule. Browsers enforce it. It stops a page from one origin from reading data that belongs to another origin. CORS (Cross-Origin Resource Sharing) is the mechanism that lets a server relax the policy for specific origins.
What an origin is
An origin is the combination of scheme, host, and port. Two URLs are same-origin only if all three match exactly.
| URL compared with `https://example.com/app` | Same origin? | Reason |
|---|---|---|
| `https://example.com/other?x=1` | Yes | Path and query do not matter |
| `http://example.com/app` | No | Different scheme |
| `https://api.example.com/app` | No | Different host (subdomains count) |
| `https://example.com:8443/app` | No | Different port (default for https is 443) |
The browser sends the page's origin in the Origin request header on cross-origin requests and on some same-origin ones, such as POST. The value has no path, for example Origin: https://app.example.com.
What the policy blocks and what it allows
SOP mostly blocks reading. It does not stop most requests from being sent.
- Blocked: JavaScript reading the response of a cross-origin
fetchorXMLHttpRequest. Also blocked: reading the DOM of a cross-origin iframe. - Allowed: embedding cross-origin images, scripts, stylesheets, and fonts. Also allowed: submitting a form to another origin, and following links.
The server still receives a cross-origin request even when the browser later hides the response. A state-changing request, such as a transfer, can therefore take effect even though the page cannot read the answer. CORS is not an access control system for your server. It only tells browsers who may read responses.
How CORS works for simple requests
For a cross-origin GET, the exchange looks like this:
GET /api/items 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
Content-Type: application/jsonThe browser compares the Origin it sent with Access-Control-Allow-Origin in the response. If the header matches the origin or is *, the script may read the body. If the header is missing or different, the browser discards the response and the script sees a network error. The console shows a CORS message with more detail than the script gets.
Preflight requests
Some requests could cause side effects the server never expected from a browser. For these the browser first asks permission with a preflight, an automatic OPTIONS request. A preflight is sent when the request uses any of these:
- A method other than
GET,HEAD, orPOST. - A custom header, such as
Authorization, or a non-safelisted header. - A
Content-Typeother thanapplication/x-www-form-urlencoded,multipart/form-data, ortext/plain. This includesapplication/json.
The preflight request looks like this:
OPTIONS /api/items HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-typeThe server answers with what it permits:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600Access-Control-Max-Age lets the browser cache the preflight result for that many seconds, which avoids an extra round trip on every call. If the preflight fails, the browser never sends the real request.
Credentials
By default, cross-origin fetch sends no cookies and ignores Set-Cookie. To include them, the page opts in and the server must agree:
const response = await fetch("http://localhost:3000/api/items", {
method: "PUT",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify({ name: "pen" }),
});
console.log(response.status, await response.json());The response must contain Access-Control-Allow-Credentials: true. With credentials, the browser rejects Access-Control-Allow-Origin: * and the wildcard forms of the other allow headers. The server must name the exact origin. Cookie rules such as SameSite still apply on top of CORS, so a cookie may be withheld even when CORS succeeds.
A server that handles CORS
This Node.js server allows two specific origins. Run it with node server.mjs, then call it from a page served at http://localhost:8080.
import { createServer } from "node:http";
const allowed = new Set(["http://localhost:8080", "https://app.example.com"]);
const server = createServer((req, res) => {
const origin = req.headers.origin;
if (origin && allowed.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
res.setHeader("Vary", "Origin");
if (req.method === "OPTIONS") {
res.writeHead(204, {
"Access-Control-Allow-Methods": "GET, POST, PUT",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Max-Age": "600",
});
res.end();
return;
}
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ ok: true, method: req.method }));
});
server.listen(3000);The code checks the incoming origin against an allowlist and echoes it back only when it matches. Vary: Origin tells caches that the response differs per origin. Without it, a shared cache could serve a response carrying one origin's header to another origin.
Common errors
- No
Access-Control-Allow-Originheader. The request reached the server and succeeded, but the browser hides the response. Fix it on the server, not in the page. - Wildcard with credentials.
*combined withcredentials: "include"fails. Echo a validated origin instead. - Preflight returns an error. An authentication layer that answers
OPTIONSwith401, or a redirect, fails the preflight. Browsers send preflights without credentials, so handleOPTIONSbefore auth checks. - Header not readable. Scripts can read only a few response headers by default. Add others to
Access-Control-Expose-Headers. - Reflecting any origin. Echoing
Originwithout checking it, together with credentials, lets any site read user data. Always validate against an allowlist. - Fixing it with a browser flag or extension. This hides the problem on your machine only. Other users' browsers still enforce the policy.
Debugging with curl and DevTools
curl does not enforce SOP, so it shows what the server actually sends. Simulate a preflight and check the response headers:
curl -i -X OPTIONS http://localhost:3000/api/items \
-H "Origin: http://localhost:8080" \
-H "Access-Control-Request-Method: PUT" \
-H "Access-Control-Request-Headers: content-type"In the browser, open the Network tab and look for the OPTIONS entry before the real request. Compare its response headers with what the request asked for.
Exercise
A page at https://app.example.com calls fetch("https://api.example.com/data", { method: "DELETE" }). The server answers the preflight with "Access-Control-Allow-Methods: GET, POST" and "Access-Control-Allow-Origin: https://app.example.com". Does the DELETE request reach the server? Why or why not?
Show answer
No. DELETE is not GET, HEAD, or POST, so the browser sends a preflight first. The preflight response does not list DELETE in Access-Control-Allow-Methods, so the browser fails the check and never sends the real DELETE request. The script sees a network error and the console shows a CORS message.
Exercise
Your API uses cookies for login. The page uses credentials: "include" and the server sends "Access-Control-Allow-Origin: *". What does the browser do, and what should the server send instead?
Show answer
The browser rejects the response because a wildcard origin is not allowed with credentials. The server should check the request's Origin against an allowlist, send that exact origin in Access-Control-Allow-Origin, send Access-Control-Allow-Credentials: true, and add Vary: Origin.