Appearance
CORS
10. What is CORS, and why do browsers enforce it?
The short answer
Browsers follow the same-origin policy: JavaScript on one origin, meaning the scheme, host and port such as https://shop.example, may not read responses from another origin. Without it, any website you visit could quietly read your email or bank pages using your cookies. CORS, cross-origin resource sharing, is the controlled exception: the server of the other origin can say, through response headers, which origins may read its responses. It is enforced by browsers to protect users; it is not a server-side access control, and tools like curl ignore it completely.
What counts as a different origin:
| Page | Request to | Same origin? |
|---|---|---|
https://shop.example | https://shop.example/api | Yes |
https://shop.example | https://api.shop.example | No: different host |
https://shop.example | http://shop.example | No: different scheme |
https://shop.example | https://shop.example:8443 | No: different port |
What CORS actually controls. The browser usually still sends the request; CORS decides whether your JavaScript may read the response. With CORS headers missing, the response arrives at the browser, but the page sees a CORS error instead of the data.
What CORS is not:
| Misunderstanding | Reality |
|---|---|
| "CORS protects my API" | It protects users' browsers; attackers call your API directly with curl |
| "Fix CORS on the front end" | Only the server's response headers can allow cross-origin reads |
| "CORS stops CSRF" | Simple form posts are sent anyway; use SameSite cookies and tokens (the CSRF question) |
11. What is a CORS preflight request, and why is the OPTIONS method used?
The short answer
For requests that could have side effects a normal web form could not produce, such as a PUT or DELETE, a JSON body, or custom headers like Authorization, the browser first sends an OPTIONS request asking the server whether the real request is allowed, with the method and headers it intends to use. Only if the server answers with matching Access-Control-Allow-* headers does the browser send the real request. OPTIONS is used because it is the HTTP method for asking what a resource supports, and it has no side effects.
PATCH with these headers is allowed. ② The server says yes, and for how long to remember it. ③ The real request goes out. ④ The response carries the allow header again, so the page may read it.Simple requests skip the preflight. A GET, HEAD or POST with only standard headers and a body type that an HTML form could send, application/x-www-form-urlencoded, multipart/form-data or text/plain, is sent directly. CORS only decides whether the page may read the response.
Requests that trigger a preflight:
| Trigger | Example |
|---|---|
Methods other than GET, HEAD, POST | PUT, PATCH, DELETE |
| A non-form content type | Content-Type: application/json |
| Custom headers | Authorization, X-Request-Id |
Cutting preflight cost: Access-Control-Max-Age: 600 lets the browser cache the answer for ten minutes, so it does not ask before every call. Or serve the API on the same origin as the front end, under /api, and there is no cross-origin request at all (the Vite deployment question).
12. How do you configure CORS to allow specific origins?
The short answer
Keep an explicit list of trusted origins and, for each request, compare its Origin header against the list; if it matches, return that exact origin in Access-Control-Allow-Origin, along with the methods and headers you allow, and Vary: Origin so caches keep separate copies per origin. In Express, the cors package does this when you give it a list or a function. Never reflect any incoming origin back unchecked, and never use * together with cookies.
ts
import cors from 'cors'
const ALLOWED_ORIGINS = new Set([
'https://shop.example',
'https://admin.shop.example',
...(config.NODE_ENV === 'development' ? ['http://localhost:5173'] : []), // (1)
])
app.use('/api', cors({
origin(origin, callback) {
if (!origin || ALLOWED_ORIGINS.has(origin)) return callback(null, true) // (2)
callback(null, false) // (3)
},
credentials: true, // (4)
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token'],
maxAge: 600, // (5)
}))- The Vite dev server's origin only in development (the Vite proxy question shows how to avoid CORS in development entirely).
- Requests without an
Origin, such as server-to-server calls and curl, are not browser cross-origin reads, so CORS does not apply. Your authentication still does. - Unknown origins get no CORS headers, so the browser blocks the page from reading the response.
- Allow cookies to be sent and the response read (question 14).
- Cache the preflight for ten minutes.
Matching rules that catch people out: compare exact strings, scheme and port included. Checking with origin.endsWith('shop.example') also allows evilshop.example; a regular expression without anchors has the same problem.
13. What does Access-Control-Allow-Origin mean?
The short answer
Access-Control-Allow-Origin is the response header in which the server tells the browser which origin may read this response. It holds either one exact origin, such as https://shop.example, or *, meaning any origin, for public data without credentials. If the header is missing or does not match the page's origin, the browser hides the response from the page's JavaScript and reports a CORS error. It can only hold one value; to allow several origins, the server picks the matching one per request.
| Value | Meaning | Allowed with cookies? |
|---|---|---|
https://shop.example | Only that origin may read it | Yes, with Allow-Credentials |
* | Any origin may read it | No (question 15) |
| Missing | No cross-origin reads | Not applicable |
https://a.example, https://b.example | Invalid: browsers reject lists | No |
The related headers:
| Header | Purpose |
|---|---|
Access-Control-Allow-Methods | Methods allowed in the preflight answer |
Access-Control-Allow-Headers | Request headers allowed |
Access-Control-Allow-Credentials: true | Cookies and auth may be included and the response read |
Access-Control-Expose-Headers | Response headers the page may read, such as ETag or Location |
Access-Control-Max-Age | How long to cache the preflight answer |
Vary: Origin | Tells caches the response differs per origin |
Vary: Origin matters with CDNs: without it, a CDN may cache the response allowed for admin.shop.example and serve it, with that header, to requests from shop.example, causing confusing CORS failures.
14. How do cookies interact with CORS and credentialed requests?
The short answer
By default, cross-origin fetch requests do not include cookies. To send them, the front end must opt in with credentials: 'include', and the server must respond with Access-Control-Allow-Credentials: true and an exact origin, not *; otherwise the browser hides the response. Separately, the cookie itself must be allowed to travel cross-site: it needs SameSite=None; Secure if the API is on a different site, or the browser will not attach it at all. Both the CORS headers and the cookie attributes must line up.
ts
// front end on https://shop.example
await fetch('https://api.shop.example/cart', { credentials: 'include' }) // (1)
// API on https://api.shop.example
res.set('Access-Control-Allow-Origin', 'https://shop.example') // (2)
res.set('Access-Control-Allow-Credentials', 'true')
res.cookie('session', id, { httpOnly: true, secure: true, sameSite: 'lax' }) // (3)- Opt in to cookies for this cross-origin request.
- An exact origin and allow-credentials, or the browser discards the response.
- Same site or not?
shop.exampleandapi.shop.exampleare different origins but the same site, soSameSite=Laxcookies are still sent. A front end onshop-web.examplecallingapi.shop.exampleis cross-site, and the cookie would needSameSite=None; Secure, with CSRF protection.
Origin versus site, the distinction behind most cookie confusion:
| Origin | Site | |
|---|---|---|
| Made of | Scheme, full host, port | Scheme and registrable domain |
https://shop.example vs https://api.shop.example | Different | Same |
| Governs | CORS, same-origin policy | Which cookies SameSite allows |
The simplest working setup puts the front end and API on the same origin, https://shop.example and https://shop.example/api, which removes CORS and cross-site cookie questions entirely.
15. Why can't a credentialed CORS response use a wildcard origin?
The short answer
Because * combined with credentials would let every website in the world read responses made with the user's cookies, which is exactly what the same-origin policy exists to prevent: any page could read the user's account data from your API. So the specification forbids it, and browsers reject Access-Control-Allow-Origin: * on any request that includes credentials. The server must name the one origin it trusts, which forces you to decide deliberately who may read authenticated data.
The tempting but dangerous workaround is to copy the request's Origin header straight back:
ts
res.set('Access-Control-Allow-Origin', req.get('Origin')!) // reflects ANY origin
res.set('Access-Control-Allow-Credentials', 'true')This has the same effect as the forbidden wildcard: an attacker's page at https://evil.example sends a credentialed request, gets its own origin reflected, and reads the victim's data. Always check against an allow-list first (question 12).
Public, cookie-free data can use * safely, such as a public product catalogue API that needs no authentication.
16. What are common causes of CORS errors?
The short answer
The server did not send Access-Control-Allow-Origin for this origin; the preflight OPTIONS request got an error, a redirect or a login page instead of an allow response; the requested method or a header such as Authorization is not in the allowed lists; credentials were included but the server answered with * or without Allow-Credentials; the origin differs slightly, such as http versus https or a different port; or an error response, such as a 500 from the framework or proxy, was sent without the CORS headers, so the real error is hidden behind a CORS message.
| Symptom in the console | Usual cause | Fix |
|---|---|---|
| "No Access-Control-Allow-Origin header" | Origin not allowed, or CORS middleware not running on that route | Add the origin; mount CORS before routes and on error responses |
| "Response to preflight request doesn't pass" | OPTIONS hits authentication and gets 401, or a redirect | Let OPTIONS through before auth; answer with 204 |
| "Request header field authorization is not allowed" | Header missing from Allow-Headers | Add it |
| "Wildcard cannot be used with credentials" | * plus credentials: 'include' | Return the exact origin |
| Works locally, fails in production | Different origin in production; proxy strips headers | Add the production origin; check the proxy |
CORS error on what is really a 500 | Error handler runs before CORS headers are set | Make sure CORS headers are added to error responses too |
How to debug quickly: open the browser's Network tab, find the OPTIONS request if there is one, and compare its request headers, Origin, Access-Control-Request-Method and Access-Control-Request-Headers, with the response's Access-Control-Allow-* headers. The mismatch is almost always visible there.
Remember the order in Express: CORS middleware must run before authentication and before routes, or preflight requests are rejected before CORS has a chance to answer (the middleware order question).