Kind: Function
Source: src/middleware/request-id/request-id.ts
Part of: Middleware
Request ID Middleware for Hono.
requestId is Hono middleware that assigns an identifier to each incoming request. It makes the identifier available through the request context and returns it in the response header so logs, handlers, and clients can reference the same request.
Signature
tsfunction requestId({
limitLength = 255,
headerName = 'X-Request-Id',
generator = () => crypto.randomUUID(),
}: RequestIdOptions): MiddlewareHandler
Parameters
| Name | Type |
|---|---|
| `{ | |
| limitLength = 255, | |
| headerName = 'X-Request-Id', | |
| generator = () => crypto.randomUUID(), | |
| }` | RequestIdOptions |
Returns: MiddlewareHandler
Diagram
mermaidgraph LR Client[Client Request] --> Middleware[requestId Middleware] Middleware --> Context[Hono Context: requestId] Middleware --> Handler[Route Handler] Handler --> Response[Response with Request ID Header]
Usage
tsimport { Hono } from 'hono'
import { requestId } from 'hono/request-id'
const app = new Hono()
app.use('*', requestId())
app.get('/status', (c) => {
const id = c.get('requestId')
return c.json({
requestId: id,
status: 'ok',
})
})
export default app
AI Coding Instructions
- Register
requestId()before route handlers that need access toc.get('requestId'). - Use the request ID when writing logs or reporting errors so related events can be correlated.
- Preserve the response request ID header when adding middleware that creates or replaces responses.
- Avoid generating separate request IDs inside handlers; read the value already stored on the Hono context.
Was this page helpful?