With the cors package in an Express 5 API, how do the origin and credentials options combine for a browser frontend that sends cookies?
answer
- default origin is a wildcard
- credentials needs a concrete origin
- disallowed origin: header omitted
- app-level mount answers preflights
basics
~20 sIn an Express 5 API, cors({ credentials: true }) alone still sends Access-Control-Allow-Origin: *, which browsers refuse on cookie-carrying requests. Set origin to the exact frontend origin, an array, a RegExp or a callback, so a matched origin is echoed.
solid answer
~40 sThe `cors` package defaults to `origin: '*'`, methods `GET,HEAD,PUT,PATCH,POST,DELETE` and `optionsSuccessStatus: 204`. `credentials: true` only adds `Access-Control-Allow-Credentials: true`; it does not change the origin, so a browser rejects the credentialed response that still says `*`. Give `origin` a string, an array of strings and RegExps, or a callback `(origin, cb)`; with an array, a RegExp or a callback the package echoes the request's origin when it matches and adds `Vary: Origin`. A non-matching origin still reaches your handler, which runs and responds: cors only omits the header, and the browser hides the response from the page. Mounted with `app.use(cors(options))` it answers every `OPTIONS` preflight itself with 204. Applied to single routes instead, it only answers a preflight when an `OPTIONS` route for the same path runs it too.
go deeper
Recall that cors() defaults to a wildcard origin and that a frontend sending cookies needs an explicit origin plus credentials: true.
Explain each origin form, string, array, RegExp, callback and true, the Vary: Origin header, and how the app-level mount answers OPTIONS with 204.
Diagnose the failures you meet in production: a wildcard with credentials, a disallowed origin whose writes still run, and a preflight that never reaches a cors applied only to the PUT route.
Decide where allow-lists live and who owns them, and when serving the frontend same-origin removes CORS from the design entirely.
## What the package does `cors` is the Express-ecosystem middleware that writes **CORS response headers**. Its README is blunt about scope: it sets headers, it does not block requests. Browsers enforce CORS by reading those headers and deciding whether page JavaScript may see the response; command-line clients and other servers ignore them. So the options are about what the API **tells the browser**, not about who may call it. Calling `cors()` with no options is equivalent to: ```json { "origin": "*", "methods": "GET,HEAD,PUT,PATCH,POST,DELETE", "preflightContinue": false, "optionsSuccessStatus": 204 } ``` ## The origin option | `origin` value | Header the package sends | |---|---| | `'*'` (default) or unset | `Access-Control-Allow-Origin: *` | | a string such as `'https://app.example.com'` | that exact string, plus `Vary: Origin`, whatever the request sent | | an array of strings and `RegExp`s, or one `RegExp` | the request's own `Origin` if it matches, plus `Vary: Origin`; nothing if it does not | | `true` | the request's `Origin`, whatever it is | | a function `(origin, callback)` | whatever value the callback returns, which can be loaded from configuration; `false` or an error means no CORS headers | | `false` | no CORS headers at all | `Vary: Origin` matters because the response now differs by caller, and a shared cache must not hand one origin's answer to another. Reflecting every origin with `true` is a known misconfiguration covered by the CORS-misconfiguration material; with credentials it hands any site read access to signed-in responses. ## The credentials trap `credentials: true` adds `Access-Control-Allow-Credentials: true` and nothing else. The common broken setup is: ```js app.use(cors({ credentials: true })); ``` The origin is still the default `'*'`, so the response says `Access-Control-Allow-Origin: *` together with `Allow-Credentials: true`. Browsers refuse that combination for a request that carries cookies or HTTP authentication, so the frontend's `fetch(url, { credentials: 'include' })` fails even though the server logged a 200. The fix is a concrete origin: ```js app.use(cors({ origin: ['https://app.example.com'], credentials: true })); ``` Why credentialed CORS requires a specific origin is protocol material that the CORS-credentials lesson covers; here the point is which package option produces which header. ## What happens to a disallowed origin With an allow-list, a request from `https://evil.example.net` is **not rejected**. The package skips `Access-Control-Allow-Origin`, calls `next()`, and the route handler runs, changes data if it is a write, and responds. The browser then hides the body from the calling page. Two consequences follow: - CORS is not access control; authentication and authorization still protect the API; - a state-changing request that needs no preflight can still have side effects, which is why cross-site request forgery defences exist separately. ## Preflights A request with a method outside the simple set, or with headers such as `Authorization`, triggers an `OPTIONS` **preflight**. When `cors` is mounted for the whole app with `app.use(cors(options))`, it answers every `OPTIONS` request itself: it writes the origin, credentials, `Access-Control-Allow-Methods` and `Access-Control-Allow-Headers` headers (by default it reflects `Access-Control-Request-Headers`), sets `optionsSuccessStatus` (204) and `Content-Length: 0`, and ends the response. `preflightContinue: true` passes the request on instead. `maxAge` adds `Access-Control-Max-Age` so browsers cache the preflight, and `exposedHeaders` lets page code read response headers such as a pagination header. If `cors` is applied to individual routes instead, a preflight only receives these headers when an `OPTIONS` route for the same path runs `cors` as well, for example `app.options('/orders/:id', cors(options))` beside the `app.put` that needs it. Mounting the middleware app-wide avoids that bookkeeping, and is the usual choice for an API whose routes all share one policy. ## A checklist for a cookie-carrying frontend 1. Set `origin` to the exact frontend origin, or an array or callback built from configuration; scheme and port are part of the origin, so `https://app.example.com` and `http://app.example.com` differ. 2. Set `credentials: true`, and make the frontend send `credentials: 'include'`. 3. Leave `allowedHeaders` unset to reflect what the browser asks for, or list headers such as `Content-Type` and `Authorization` explicitly. 4. Add `exposedHeaders` for any response header the page must read, and `maxAge` to cut repeated preflights. 5. Check in the browser's network panel that the response carries the echoed origin, `Access-Control-Allow-Credentials: true` and `Vary: Origin`. ## When you need none of it If the Express app serves the built frontend itself, so the page and the API share a scheme, host and port, every call is same-origin and no CORS header is needed. The package is only for frontends on another origin, such as `app.example.com` calling `api.example.com`.
- How do you load the cors allow-list from configuration without reflecting every origin?Pass `origin` a callback: `origin: (origin, cb) => cb(null, allowed.includes(origin) ? origin : false)`, where `allowed` comes from configuration. Returning the matched origin makes the package echo it with `Vary: Origin`; returning `false` leaves the header off. Avoid `origin: true`, which echoes any caller and, combined with `credentials: true`, lets every site read signed-in responses.
- Why do some APIs set optionsSuccessStatus to 200 instead of the default?The package defaults to answering a preflight with 204 and `Content-Length: 0`. Its README notes that some legacy browsers and smart-TV clients choke on 204, so `optionsSuccessStatus: 200` is the workaround. Modern browsers accept either; the status does not change which origins are allowed.
- cors({ credentials: true }) is enough for a cookie-sending frontend.
- The cors package rejects requests from origins that are not on its list.
- origin: true is a safe allow-list because it only echoes real origins.
- A fixed string origin is only sent back when the request's Origin matches it.
- With app.use(cors()), preflight OPTIONS requests are passed on to the route handlers.