跳转到正文

Request ID 中间件 ​

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

说明

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
}>()

设置请求 ID ​

在请求头(默认 X-Request-Id)中设置自定义请求 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()。

平台特有的请求 ID ​

某些平台(如 AWS Lambda)已经为每个请求生成各自的请求 ID。 如果不额外配置,此中间件无法识别这些特定的请求 ID, 而是生成新的请求 ID,查看应用日志时可能因此产生混淆。

要统一这些 ID,请通过 generator 函数获取平台特有的请求 ID,并在此中间件中使用。

基于 MIT 许可证发布。