Skip to Content
Middleware (guards)request-id.middleware.ts

request-id.middleware.ts

Gives every request a correlation id so logs, errors, and rate-limit events can be tied back to a single client call.

What it does

  1. Looks at the incoming X-Request-Id (or X-Request-ID) header.
  2. If the header is missing, empty, or longer than 128 chars → generates a UUID (crypto.randomUUID()).
  3. Stores the chosen id on c.set('requestId', ...) so the rest of the stack can read it.
  4. Echoes the same value back on the response as X-Request-Id after the handler finishes.
c.get('requestId') // string — always available downstream

Where it is mounted

In src/index.ts, before any route, so every endpoint (including /health, /ready, /internal/*) gets an id:

app.use('*', requestIdMiddleware)

Who consumes the id

  • The global error handler (app.onError) attaches the id to the JSON error response so users can quote it to support.
  • rate-limit.middleware.ts writes it on every RateLimitEvent and on the 429 body.
  • Structured logs in lib/logger.ts include it for grep-able traces.

CORS exposure

The id is added to exposeHeaders in the CORS config in index.ts, so browser code (extension, vite-frontend, admin-frontend) can read it from Response.headers.get('X-Request-Id').

Last updated on