Skip to content

Commit 6e61599

Browse files
authored
docs: Add example of using AsyncLocalStorage to README (#47)
* Add example of using AsyncLocalStorage to README * Change AsyncLocalStorage to an example of using Context Storage Middleware * Change get from context to the correct description * Remove description of saving Headers from the context usage example * Fix type definition for Variables
1 parent dabf6e0 commit 6e61599

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -335,6 +335,49 @@ export const getLoadContext: GetLoadContext = ({ context }) => {
335335
}
336336
```
337337

338+
## AsyncLocalStorage
339+
340+
You can use AsyncLocalStorage, which is supported by Node.js, Cloudflare Workers, etc.
341+
You can easily store context using Hono's Context Storage Middleware.
342+
343+
```ts
344+
// server/index.ts
345+
import { Hono } from 'hono'
346+
import { contextStorage } from 'hono/context-storage'
347+
348+
export interface Env {
349+
Variables: {
350+
message: string
351+
// db: DatabaseConnection // It's also a good idea to store database connections, etc.
352+
}
353+
}
354+
355+
const app = new Hono<Env>()
356+
357+
app.use(contextStorage())
358+
359+
app.use(async (c, next) => {
360+
c.set('message', 'Hello!')
361+
362+
await next()
363+
})
364+
365+
export default app
366+
```
367+
368+
You can retrieve and process the context saved in Hono from Remix as follows:
369+
370+
```ts
371+
// app/routes/_index.tsx
372+
import type { Env } from 'server'
373+
import { getContext } from 'hono/context-storage' // It can be called anywhere for server-side processing.
374+
375+
export const loader = () => {
376+
const message = getContext<Env>().var.message
377+
...
378+
}
379+
```
380+
338381
## Auth middleware for Remix routes
339382

340383
If you want to add Auth Middleware, e.g. Basic Auth middleware, please be careful that users can access the protected pages with SPA tradition. To prevent this, add a `loader` to the page:

0 commit comments

Comments
 (0)