Skip to content

请求 ID 中间件

🌐 Request ID Middleware

请求 ID 中间件为每个请求生成一个唯一的 ID,你可以在处理程序中使用该 ID。

🌐 Request ID Middleware generates a unique ID for each request, which you can use in your handlers.

INFO

Node.js:这个中间件使用 crypto.randomUUID() 来生成 ID。全局 crypto 是在 Node.js 20 或更高版本中引入的。因此,在早于该版本的环境中可能会发生错误。在这种情况下,请指定 generator。但是,如果你使用 Node.js 适配器,它会自动在全局设置 crypto,所以这不是必需的。

导入

🌐 Import

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

用法

🌐 Usage

你可以通过 requestId 变量访问请求 ID,该变量在应用了请求 ID 中间件的处理器和中间件中可用。

🌐 You can access the Request ID through the requestId variable in the handlers and middleware to which the Request ID Middleware is applied.

ts
const app = new Hono()

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

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

如果你想明确指定类型,导入 RequestIdVariables 并将其传递到 new Hono() 的泛型中。

🌐 If you want to explicitly specify the type, import RequestIdVariables and pass it in the generics of new Hono().

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

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

设置请求 ID

🌐 Set Request ID

你可以在请求头中设置自定义请求ID(默认:X-Request-Id),中间件将使用该值而不是生成新的ID:

🌐 You set a custom request ID in the header (default: X-Request-Id), the middleware will use that value instead of generating a new one:

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 选项 设置为空字符串。

🌐 If you want to disable this feature, set headerName option to an empty string.

选项

🌐 Options

optional 限制长度: number

请求 ID 的最大长度。默认值是 255

🌐 The maximum length of the request ID. The default is 255.

optional headerName: string

用于请求 ID 的头名称。默认值是 X-Request-Id

🌐 The header name used for the request ID. The default is X-Request-Id.

optional 生成器: (c: Context) => string

请求 ID 生成函数。默认情况下,它使用 crypto.randomUUID()

🌐 The request ID generation function. By default, it uses crypto.randomUUID().

特定平台的请求 ID

🌐 Platform specific Request IDs

一些平台(例如 AWS Lambda)已经为每个请求生成它们自己的请求 ID。
在没有任何额外配置的情况下,这个中间件无法感知这些特定的请求 ID
并会生成一个新的请求 ID。在查看你的应用日志时,这可能会导致混淆。

🌐 Some platform (such as AWS Lambda) already generate their own Request IDs per request. Without any additional configuration, this middleware is unaware of these specific Request IDs and generates a new Request ID. This can lead to confusion when looking at your application logs.

要统一这些 ID,请使用 generator 函数来捕获特定平台的请求 ID 并在此中间件中使用它。

🌐 To unify these IDs, use the generator function to capture the platform specific Request ID and to use it in this middleware.

🌐 Platform specific links

Hono 中文网 - 粤ICP备13048890号