Skip to content

Commit

Permalink
docs(context-storage): improve
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe committed Sep 11, 2024
1 parent 32fd22c commit 1d007e2
Showing 1 changed file with 36 additions and 2 deletions.
38 changes: 36 additions & 2 deletions docs/middleware/builtin/context-storage.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
# Context Storage Middleware

The Context Storage Middleware stores the Hono `Context` in the `AsyncLocalStorage`, to make it globally accessible.
The Context Storage Middleware stores the Hono `Context` in the `AsyncLocalStorage`, to make it globally accessible.

::: info
**Note** This middleware uses `AsyncLocalStorage`. The runtime should support it.

**Cloudflare Workers**: To enable `AsyncLocalStorage`, add the [`nodejs_compat` or `nodejs_als` flag](https://developers.cloudflare.com/workers/configuration/compatibility-dates/#nodejs-compatibility-flag) to your `wrangler.toml` file.
:::

## Import

Expand All @@ -11,6 +17,8 @@ import { contextStorage, getContext } from 'hono/context-storage'

## Usage

The `getContext()` will return the current Context object if the `contextStorage()` is applied as a middleware.

```ts
type Env = {
Variables: {
Expand All @@ -22,9 +30,35 @@ const app = new Hono<Env>()

app.use(contextStorage())

app.get('/', (c) => c.text(getMessage())
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())
})
```

On Cloudflare Workers, you can access the bindings outside the handler.

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

0 comments on commit 1d007e2

Please sign in to comment.