Same-origin policy and CORS: a browser-enforced policy
Same origin means identical scheme, host, and port. Any difference makes it cross-origin:
| Page URL | Request URL | Same origin? | Why |
|---|---|---|---|
https://app.example.com/page |
https://app.example.com/api |
✅ | Same scheme, host, and port |
https://app.example.com |
http://app.example.com |
❌ | Different scheme |
https://app.example.com |
https://api.example.com |
❌ | Different host |
https://app.example.com |
https://app.example.com:8443 |
❌ | Different port |
The key insight: the same-origin policy restricts reading responses, not sending requests. Cross-origin form posts, <img> loads, and <script> includes all reach the server and execute; CORS only relaxes whether JavaScript may see the response body.
Two conclusions follow:
- CORS is browser behaviour. The server handles the request as usual; the browser decides afterwards whether to hand the response to the page.
curl, Postman, and server-side scripts ignore it entirely. - CORS is not access control. It cannot stop anyone from calling your API; it only stops another site from reading your response inside a user's browser. Real authorization belongs on the server.
Simple requests and preflight
Browsers split requests by whether they can cause side effects.
Simple requests
When all of the following hold, the browser sends the request directly with no preflight:
- The method is
GET,HEAD, orPOST; - Only safelisted headers are used (
Accept,Accept-Language,Content-Language,Content-Type, and similar); Content-Typeis limited totext/plain,multipart/form-data, orapplication/x-www-form-urlencoded.
Note: no preflight does not mean safe. The request has already left and the server has already acted; without a correct Access-Control-Allow-Origin, the browser merely refuses to let the page read it. Protecting against side effects is a CSRF and API-design concern.
Preflight
A non-simple method, a custom header (Authorization, X-Requested-With), or Content-Type: application/json triggers an OPTIONS first, carrying Origin, Access-Control-Request-Method, and Access-Control-Request-Headers. The server must answer three things before the real request goes out:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Vary: Origin
The usual preflight failure is not a wrong CORS header but an OPTIONS request blocked by an authentication middleware (401), redirected by a gateway, or answered 405 by a router. Preflights carry no business credentials yet must be allowed — the step most often missed.
Six response headers, three of them routinely misconfigured
| Header | Purpose | Common mistake |
|---|---|---|
Access-Control-Allow-Origin |
Which origin may read the response | Reflecting any Origin; * with credentials |
Access-Control-Allow-Credentials |
Whether cookies may travel | Paired with *, which the browser rejects |
Access-Control-Allow-Methods |
Methods allowed by the preflight | Missing the method actually used |
Access-Control-Allow-Headers |
Request headers allowed | Missing Authorization or a custom header |
Access-Control-Expose-Headers |
Response headers JS may read | Forgetting X-Total-Count and similar |
Access-Control-Max-Age |
How long to cache the preflight | Set too long; old results outlive config changes |
Three hard rules:
Access-Control-Allow-Originmust be one origin or*, never a comma-separated list. For multiple origins, match the requestOriginagainst an allowlist.- With credentials (cookies or HTTP auth),
Access-Control-Allow-Origincannot be*andAccess-Control-Allow-Credentialsmust betrue. - Whenever the response varies with
Origin, sendVary: Origin, or a CDN or proxy will cache site A's response for site B.
The most dangerous configuration is "reflect the Origin and allow credentials":
// ❌ Any site can read your API with the user's cookies
res.setHeader('Access-Control-Allow-Origin', req.headers.origin)
res.setHeader('Access-Control-Allow-Credentials', 'true')
That is semantically "disable the same-origin policy". It is worse than no CORS at all: no CORS merely hides the response, while this hands every logged-in user's response to any site.
Four working configurations
Nginx: same-origin reverse proxy (recommended)
The most robust option is not configuring CORS but making the page and API same-origin: proxy app.example.com/api to the backend so the front end calls /api and the browser never sees a cross-origin request.
When cross-origin is genuinely required, here is the minimum working configuration:
# Allowlist: echo only matching Origins, otherwise return nothing
map $http_origin $cors_origin {
default "";
"~^https://(www\.)?example\.com$" $http_origin;
}
server {
location /api/ {
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS" always;
add_header Access-Control-Allow-Headers "Content-Type, Authorization" always;
add_header Content-Length 0;
add_header Content-Type text/plain;
return 204;
}
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials "true" always;
add_header Vary Origin always;
proxy_pass http://backend;
}
}
Never omit always: without it, add_header only applies to 2xx/3xx responses, so a 4xx/5xx backend reply loses the CORS headers and the front end sees only "CORS error", hiding the real failure.
Re-declaring add_header inside if replaces the outer set: Nginx inheritance means any add_header at a deeper level drops all inherited ones, so the OPTIONS branch must repeat every header it needs.
Express: allowlist middleware
const allowlist = new Set(['https://app.example.com'])
app.use((req, res, next) => {
const origin = req.headers.origin
if (allowlist.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.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
return res.sendStatus(204) // The preflight must be 2xx and must not hit auth
}
next()
})
Do not use cors({ origin: true, credentials: true }) — origin: true reflects any origin, exactly the dangerous configuration above. Even with the official cors package, pass a whitelist function rather than a boolean.
Spring Boot: the essentials
- Use
allowedOriginswith exact values; when wildcards are unavoidable, useallowedOriginPatternsand never combine it withallowCredentials(true)into "any origin plus credentials". - With Spring Security, the
CorsFiltermust sit before the authentication filter, or the preflight dies at a 401. - Permit
OPTIONSin the security configuration and authenticate the real request afterwards. - Do not keep both a global
addCorsMappingsand per-controller@CrossOrigin; the more permissive one tends to win.
Wildcard subdomains: escape the regex
The *.example.com requirement is often written as endsWith('example.com'), which permits evilexample.com:
// ❌ A suffix check is bypassed by evilexample.com
if (origin.endsWith('example.com')) { /* allow */ }
// ✅ Parse, then compare hostnames with a dot boundary
function isAllowed(origin) {
try {
const { protocol, hostname } = new URL(origin)
return protocol === 'https:' &&
(hostname === 'example.com' || hostname.endsWith('.example.com'))
} catch { return false }
}
The leading dot makes evilexample.com fail. In a regex, escape the dot in example.com as \. and anchor it with ^...$.
Watch out for Origin: null: file:// pages, sandboxed iframes, and some redirects send it. Never put null in an allowlist — that opens the door to local files and arbitrary sandboxed pages.
Debugging: walk the response headers
The browser only says blocked by CORS policy; the actual cause is in the response. Check in order:
- Did the preflight succeed? Look at the
OPTIONSstatus in the network panel. 401 / 302 / 405 are configuration problems, not front-end ones. - Does
Access-Control-Allow-Originexactly equal the currentOrigin? A different port, a missingwww, or a trailing slash all count as mismatches. - With credentials, is
Allow-Credentials: truepresent andAllow-Originnot*? - Does the custom header appear in
Allow-Headersand the method inAllow-Methods? - Is
Vary: Originmissing? It shows up as intermittent success or failure across refreshes and CDN nodes. - Is the response a redirect? Preflight responses may not redirect; an
http → httpsjump fails the preflight outright.
Reproducible results
No browser needed; curl shows exactly what the server returns:
curl -i -X OPTIONS https://api.example.com/api/users \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: content-type, authorization"
Check four lines: a 2xx status, an exact echo in Access-Control-Allow-Origin, POST present in Access-Control-Allow-Methods, and authorization present in Access-Control-Allow-Headers. Miss any one and the browser blocks the real request. Header semantics are in the HTTP headers cheat sheet.