$ cat docs/middleware/cors.md
CORSCORS
Cross-Origin Resource Sharing for browser clients: answer preflights and attach the headers that let an allowed origin read a response.Cross-Origin Resource Sharing para clientes de navegador: responda preflights e anexe os headers que permitem a uma origem autorizada ler a resposta.
What it doesO que faz
cors(options?: CorsOptions): MiddlewareHandler. A preflight (OPTIONS with
access-control-request-method) is answered with 204 without calling next().
A reflected origin adds vary: origin; a disallowed origin simply gets no
access-control-allow-origin (the browser enforces the policy).
cors(options?: CorsOptions): MiddlewareHandler. Um preflight (OPTIONS com
access-control-request-method) é respondido com 204 sem chamar next(). Uma origem
refletida adiciona vary: origin; uma origem não permitida apenas não recebe
access-control-allow-origin (o navegador aplica a política).
Install and orderInstalar e ordenar
pnpm add @tupik/middleware
Register it with .use() before the routes it should protect. app.use(cors()) covers every
route, runs before module middleware and also answers preflights for paths without an OPTIONS route.
On a module, a preflight only reaches the middleware when the router matches an OPTIONS route, so
declare .options('/*path', ...) in the same module.
Registre com .use() antes das rotas que ele deve proteger. app.use(cors()) cobre todas as
rotas, roda antes dos middlewares do módulo e também responde preflights de caminhos sem rota OPTIONS.
Num módulo, um preflight só chega ao middleware quando o roteador casa uma rota OPTIONS, então declare
.options('/*path', ...) no mesmo módulo.
ExampleExemplo
import { cors } from '@tupik/middleware';
createModule('/api')
.use(cors({
origin: (origin) => origin.endsWith('.example.com'), // string, list or predicate
allowedHeaders: ['content-type', 'authorization'],
exposedHeaders: ['ratelimit-remaining'],
credentials: true,
maxAge: 600,
}))
.options('/*path', { access: 'public', handler: () => undefined })
.get('/items', { access: 'public', handler: () => [] });
// OPTIONS /api/items + origin + access-control-request-method: GET
// → 204, access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
// vary: originimport { cors } from '@tupik/middleware';
createModule('/api')
.use(cors({
origin: (origin) => origin.endsWith('.example.com'), // string, lista ou predicado
allowedHeaders: ['content-type', 'authorization'],
exposedHeaders: ['ratelimit-remaining'],
credentials: true,
maxAge: 600,
}))
.options('/*path', { access: 'public', handler: () => undefined })
.get('/items', { access: 'public', handler: () => [] });
// OPTIONS /api/items + origin + access-control-request-method: GET
// → 204, access-control-allow-methods: GET,HEAD,PUT,PATCH,POST,DELETE
// vary: origin APIAPI
| OptionOpção | TypeTipo | Default / behaviorPadrão / comportamento |
|---|---|---|
origin | CorsOrigin | '*' (never reflects). string, list or predicate reflect the Origin and add vary: origin.'*' (nunca reflete). string, lista ou predicado refletem o Origin e adicionam vary: origin. |
methods | readonly string[] | GET,HEAD,PUT,PATCH,POST,DELETE (preflight only).GET,HEAD,PUT,PATCH,POST,DELETE (só no preflight). |
allowedHeaders | readonly string[] | Echoes access-control-request-headers when omitted.Ecoa access-control-request-headers quando omitido. |
exposedHeaders | readonly string[] | access-control-expose-headers on actual responses.access-control-expose-headers nas respostas reais. |
credentials | boolean | Sends access-control-allow-credentials: true. Requires an explicit origin (throws with '*').Envia access-control-allow-credentials: true. Exige origin explícito (lança com '*'). |
allowNullOrigin | boolean | false: Origin null is never reflected.false: Origin null nunca é refletido. |
maxAge | number | Preflight access-control-max-age, in seconds.access-control-max-age do preflight, em segundos. |
type CorsOrigin = string | readonly string[] | ((origin: string) => boolean)
type CorsOrigin = string | readonly string[] | ((origin: string) => boolean)
Errors and limitsErros e limites
- With
module.use(cors()), a preflight needs a matched OPTIONS route; without one the engine answers before cors runs.app.use(cors())has no such limit. origin: '*'never reflects the request origin; combined withcredentials: trueit throws at creation.- The opaque
Origin: nullis never reflected unlessallowNullOrigin: true, even by a predicate that accepts everything. - Headers do not reach engine-generated 404, 413 or validation errors; add them in
onError/onSend.
- Com
module.use(cors()), um preflight precisa de uma rota OPTIONS casada; sem ela o engine responde antes de o cors rodar.app.use(cors())não tem esse limite. origin: '*'nunca reflete a origem da requisição; comcredentials: truelança na criação.- O
Origin: nullopaco nunca é refletido semallowNullOrigin: true, nem por um predicado que aceita tudo. - Os headers não chegam a 404, 413 ou erros de validação gerados pelo engine; adicione-os em
onError/onSend.
When not to use itQuando não usar
Skip it for same-origin apps and server-to-server clients, where the browser policy does not apply. CORS is not authentication: pair it with jwt or your own authorization checks before exposing private data.
Dispense para apps da mesma origem e clientes servidor-a-servidor, onde a política do navegador não se aplica. CORS não é autenticação: combine com jwt ou suas próprias checagens de autorização antes de expor dados privados.