コンテンツへ移動

コンテキスト・ストレージ・ミドルウェア

コンテキスト・ストレージ・ミドルウェアは、Hono ContextAsyncLocalStorage に格納し、グローバルにアクセスできるようにします。

INFO

このミドルウェアは AsyncLocalStorage を使用します。ランタイムはこれをサポートする必要があります。

Cloudflare Workers: AsyncLocalStorage を有効にするには、nodejs_compat または nodejs_als フラグを wrangler.toml ファイルに追加します。

インポート

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

使用

getContext() は、contextStorage() がミドルウェアとして適用された場合、現在の 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()
})

// You can access the variable outside the handler.
const getMessage = () => {
  return getContext<Env>().var.message
}

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

Cloudflare Workers では、ハンドラーの外部でバインディングにアクセスできます。

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

MITライセンスに基づいてリリースされています。