Skip to content

Context Storage 中间件

Context Storage 中间件会将 Hono 的 Context 存入 AsyncLocalStorage,以便在全局范围访问。

INFO

注意:该中间件依赖 AsyncLocalStorage,需要运行环境提供支持。

Cloudflare Workers:如需启用 AsyncLocalStorage,请在 wrangler.toml 中添加 nodejs_compatnodejs_als 标志

导入

ts
import { Hono } from 'hono'
import { contextStorage, getContext } from 'hono/context-storage'

用法

在应用了 contextStorage() 中间件后,可通过 getContext() 取得当前的 Context 对象。

ts
type Env = {
  Variables: {
    message: string
  }
}

const app = new Hono<Env>()

app.use(contextStorage())

app.use(async (c, next) => {
  c.set('message', 'Hello!')
  await next()
})

// 可以在处理器之外访问变量。
const getMessage = () => {
  return getContext<Env>().var.message
}

app.get('/', (c) => {
  return c.text(getMessage())
})

在 Cloudflare Workers 中,还可以在处理器外部访问绑定(bindings)。

ts
type Env = {
  Bindings: {
    KV: KVNamespace
  }
}

const app = new Hono<Env>()

app.use(contextStorage())

const setKV = (value: string) => {
  return getContext<Env>().env.KV.put('key', value)
}

Released under the MIT License.