Skip to content

컨텍스트 저장소 미들웨어

컨텍스트 저장소 미들웨어는 Hono ContextAsyncLocalStorage에 저장하여 전역적으로 접근할 수 있게 한다.

INFO

참고 이 미들웨어는 AsyncLocalStorage를 사용한다. 런타임에서 이를 지원해야 한다.

Cloudflare Workers: AsyncLocalStorage를 활성화하려면 nodejs_compat 또는 nodejs_als 플래그wrangler.toml 파일에 추가해야 한다.

Import

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에서는 핸들러 외부에서 바인딩에 접근할 수 있다.

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.