本文へ移動

Context Storage ミドルウェア ​

Context Storage ミドルウェアは、Hono の Context を AsyncLocalStorage に保存し、グローバルにアクセスできるようにします。

情報

注意:このミドルウェアは AsyncLocalStorage を使います。ランタイムのサポートが必要です。

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

インポート ​

ts
import { Hono } from 'hono'
import {
  contextStorage,
  getContext,
  tryGetContext,
} 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()
})

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

tryGetContext ​

tryGetContext() は getContext() と同様ですが、コンテキストがない場合にエラーをスローせず、undefined を返します。

ts
const context = tryGetContext<Env>()
if (context) {
  // Context is available
  console.log(context.var.message)
}

MIT ライセンスで公開されています。