CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
Blame · Line-by-line history
request-context.ts
Each line is annotated with the commit that last touched it. Click any SHA to jump to that commit and see the surrounding change.
| 3ef4c9d | 1 | /** |
| 2 | * Request context middleware — attaches a request ID and start time to every | |
| 3 | * request. Adds the ID to the response headers for correlation + to c.get() | |
| 4 | * so downstream handlers and loggers can reference it. | |
| 5 | */ | |
| 6 | ||
| 7 | import { createMiddleware } from "hono/factory"; | |
| 8 | ||
| 9 | export type RequestContextEnv = { | |
| 10 | Variables: { | |
| 11 | requestId: string; | |
| 12 | requestStart: number; | |
| 13 | }; | |
| 14 | }; | |
| 15 | ||
| 16 | function genId(): string { | |
| 2c3ba6e | 17 | const rand = crypto.randomUUID().replace(/-/g, '').slice(0, 8); |
| 3ef4c9d | 18 | const ts = Date.now().toString(36); |
| 19 | return `${ts}-${rand}`; | |
| 20 | } | |
| 21 | ||
| 22 | export const requestContext = createMiddleware<RequestContextEnv>( | |
| 23 | async (c, next) => { | |
| 24 | const existing = c.req.header("x-request-id"); | |
| 25 | const id = existing && existing.length < 100 ? existing : genId(); | |
| 26 | c.set("requestId", id); | |
| 27 | c.set("requestStart", Date.now()); | |
| 28 | c.header("X-Request-Id", id); | |
| 29 | await next(); | |
| 30 | } | |
| 31 | ); |