Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(context-storage): improve #483

Merged
merged 1 commit into from
Sep 11, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
```