Skip to content

Request ID 中间件

Request ID 中间件会为每个请求生成唯一 ID,便于在处理器中使用。

INFO

Node.js:该中间件使用 crypto.randomUUID() 生成 ID。全局 crypto 自 Node.js 20 起才默认提供,因此更早版本可能会报错,此时可通过 generator 选项自定义生成方式。不过若使用 Node.js 适配器,它会自动在全局注入 crypto,无需额外配置。

导入

ts
import { Hono } from 'hono'
import { requestId } from 'hono/request-id'

用法

只要应用了 Request ID 中间件,就能在处理器或后续中间件中通过 requestId 变量访问该 ID。

ts
const app = new Hono()

app.use('*', requestId())

app.get('/', (c) => {
  return c.text(`Your request id is ${c.get('requestId')}`)
})

如果希望显式指定类型,可导入 RequestIdVariables 并在 new Hono() 的泛型参数中传入:

ts
import type { RequestIdVariables } from 'hono/request-id'

const app = new Hono<{
  Variables: RequestIdVariables
}>()

自定义 Request ID

当请求头中包含自定义 ID(默认读取 X-Request-Id)时,中间件会直接使用该值而不再生成新的 ID:

ts
const app = new Hono()

app.use('*', requestId())

app.get('/', (c) => {
  return c.text(`${c.get('requestId')}`)
})

const res = await app.request('/', {
  headers: {
    'X-Request-Id': 'your-custom-id',
  },
})
console.log(await res.text()) // your-custom-id

若要禁用该行为,可将 headerName 选项 设为空字符串。

选项

optional limitLength:number

请求 ID 的最大长度,默认值为 255

optional headerName:string

用于读取请求 ID 的请求头名称,默认值为 X-Request-Id

optional generator:(c: Context) => string

自定义的请求 ID 生成函数,默认使用 crypto.randomUUID()

Released under the MIT License.