$ cat docs/middleware/request-id.md
Request IDID de requisição
Give every matched request one correlation id: echo it on a response header and expose it to handlers through ctx.rawStore.Dê a cada requisição casada um id de correlação: ecoe em um header de resposta e exponha aos handlers via ctx.rawStore.
What it doesO que faz
requestId(options?: RequestIdOptions): MiddlewareHandler. It chooses one id per request and always
stores it at ctx.rawStore.get('requestId'). Unless expose is false, the same value is set
on the response header (default x-request-id). The default generator is
globalThis.crypto.randomUUID(). With trustIncoming: true, an incoming value is reused only
when it matches ^[A-Za-z0-9._~-]{1,128}$; a longer or unsafe value is replaced by a generated id.
requestId(options?: RequestIdOptions): MiddlewareHandler. Ele escolhe um id por requisição e sempre o
guarda em ctx.rawStore.get('requestId'). A menos que expose seja false, o mesmo valor é
definido no header de resposta (padrão x-request-id). O gerador padrão é
globalThis.crypto.randomUUID(). Com trustIncoming: true, um valor de entrada só é reusado
quando casa com ^[A-Za-z0-9._~-]{1,128}$; um valor maior ou inseguro é trocado por um id gerado.
Install and orderInstalar e ordenar
pnpm add @tupik/middleware
Register it early with app.use(requestId()), before logger, other middleware and routes: handlers and
later middleware can then read the same value from ctx.rawStore. Only enable trustIncoming behind a proxy or
edge that strips or overwrites the header. Middleware runs on matched routes only, so engine-generated 404, 413 and
validation errors do not receive an id.
Registre cedo com app.use(requestId()), antes do logger, de outros middlewares e das rotas: handlers e
middlewares seguintes passam a ler o mesmo valor em ctx.rawStore. Só ligue trustIncoming atrás de um proxy
ou edge que remova ou sobrescreva o header. Middlewares só rodam em rotas casadas, então 404, 413 e erros de
validação gerados pelo engine não recebem id.
ExampleExemplo
import { createApp, createModule } from '@tupik/core';
import { requestId } from '@tupik/middleware';
const app = createApp();
// reuse a safe incoming id; anything else is regenerated
app.use(requestId({ header: 'x-request-id', trustIncoming: true }));
app.register(
createModule('/api').get('/orders/:id', {
access: 'public',
handler: (ctx) => ({
id: ctx.params.id,
requestId: ctx.rawStore.get('requestId'), // same id as the response header
}),
}),
);
const response = await app.fetch(
new Request('http://localhost/api/orders/42', {
headers: { 'x-request-id': 'edge-9f2c4a' },
}),
);
console.log(response.headers.get('x-request-id')); // edge-9f2c4aimport { createApp, createModule } from '@tupik/core';
import { requestId } from '@tupik/middleware';
const app = createApp();
// reuse um id de entrada seguro; qualquer outra coisa é regenerada
app.use(requestId({ header: 'x-request-id', trustIncoming: true }));
app.register(
createModule('/api').get('/orders/:id', {
access: 'public',
handler: (ctx) => ({
id: ctx.params.id,
requestId: ctx.rawStore.get('requestId'), // mesmo id do header de resposta
}),
}),
);
const response = await app.fetch(
new Request('http://localhost/api/orders/42', {
headers: { 'x-request-id': 'edge-9f2c4a' },
}),
);
console.log(response.headers.get('x-request-id')); // edge-9f2c4a APIAPI
| OptionOpção | TypeTipo | Default / behaviorPadrão / comportamento |
|---|---|---|
header | string | x-request-id. Read only when trustIncoming is on; always written when expose is true.x-request-id. Lido só quando trustIncoming está ligado; sempre escrito quando expose é true. |
generator | () => string | globalThis.crypto.randomUUID(). Called when the incoming value is absent, untrusted or unsafe.globalThis.crypto.randomUUID(). Chamado quando o valor de entrada está ausente, não é confiável ou é inseguro. |
trustIncoming | boolean | false. true reuses an incoming header value that matches the safe-id pattern.false. true reusa um valor de header de entrada que casa com o padrão de id seguro. |
expose | boolean | true. false keeps the id in rawStore without touching the response.true. false mantém o id no rawStore sem tocar na resposta. |
interface RequestIdOptions { header?, generator?, trustIncoming?, expose? }
interface RequestIdOptions { header?, generator?, trustIncoming?, expose? }
Errors and limitsErros e limites
- An empty, whitespace-bearing or non-token
header, and ageneratorthat is not a function, throwTypeErrorwhen the factory is called. - Trusted values are capped at 128 characters and limited to
A-Z a-z 0-9 . _ ~ -; anything else is regenerated, so an unsafe incoming value never becomes the id written to the configured response header orctx.rawStore. - The middleware trusts an incoming header when
trustIncomingis on: the edge must strip or overwrite it, or a client can choose its own id. - It never logs and never removes the raw request header: the incoming
x-request-idstays visible to handlers and tologger({ includeHeaders: true })unless the edge strips or overwrites it. - A raw
Responsehas its header forced (an existing value for the chosen header is replaced);expose: falseleaves onlyctx.rawStore. - A status-0 network-error response (for example
Response.error()) is returned untouched: it cannot carry the response header. - It decorates matched routes only: engine-generated 404, 413 and validation errors keep no request id.
- A generated value that is not a string or does not match the safe-id pattern falls back to a UUID.
- Generated ids need
globalThis.crypto.randomUUID(); provide ageneratoron a runtime without WebCrypto.
- Um
headervazio, com espaços ou que não seja um token, e umgeneratorque não seja função lançamTypeErrorquando a factory é chamada. - Valores confiáveis são limitados a 128 caracteres e a
A-Z a-z 0-9 . _ ~ -; qualquer outra coisa é regenerada, então um valor de entrada inseguro nunca se torna o id escrito no header de resposta configurado nem noctx.rawStore. - O middleware confia em um header de entrada quando
trustIncomingestá ligado: o edge precisa remover ou sobrescrever o header, senão o cliente escolhe o próprio id. - Ele nunca loga nem remove o header bruto da requisição: o
x-request-idde entrada continua visível aos handlers e aologger({ includeHeaders: true })a menos que o edge o remova ou sobrescreva. - Uma
Responsecrua tem o header forçado (um valor existente para o header escolhido é substituído);expose: falsedeixa só octx.rawStore. - Uma resposta de erro de rede com status 0 (por exemplo
Response.error()) é devolvida intacta: ela não pode carregar o header de resposta. - Ele decora só rotas casadas: 404, 413 e erros de validação gerados pelo engine ficam sem id de requisição.
- Um valor gerado que não seja string ou não case com o padrão de id seguro cai para um UUID.
- Ids gerados precisam de
globalThis.crypto.randomUUID(); forneça umgeneratorem runtime sem WebCrypto.
When not to use itQuando não usar
Skip it when a gateway already assigns an id and you only need to read it in the handler. Do not treat the id as
authentication, tenant identity or proof of origin: with trustIncoming on, any client can send it unless
the edge replaces it. For timing spans and trace context, use @tupik/infra's runtime tracer instead.
Dispense quando um gateway já atribui um id e você só precisa lê-lo no handler. Não trate o id como autenticação,
identidade de tenant ou prova de origem: com trustIncoming ligado, qualquer cliente pode enviá-lo a menos
que o edge o substitua. Para spans de tempo e contexto de trace, use o tracer de runtime do @tupik/infra.