Skip to content

Commit

Permalink
Change AsyncLocalStorage to an example of using Context Storage Middl…
Browse files Browse the repository at this point in the history
…eware
  • Loading branch information
chimame committed Dec 9, 2024
1 parent 8e0c4ea commit e469093
Showing 1 changed file with 18 additions and 44 deletions.
62 changes: 18 additions & 44 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,70 +338,44 @@ export const getLoadContext: GetLoadContext = ({ context }) => {
## AsyncLocalStorage

You can use AsyncLocalStorage, which is supported by Node.js, Cloudflare Workers, etc.
You can easily store context using Hono's Context Storage Middleware.

```ts
// server/context/index.ts
import { AsyncLocalStorage } from 'node:async_hooks'

export const context = new AsyncLocalStorage<ReturnType<typeof createContext>>()
// server/index.ts
import { Hono } from 'hono'
import { contextStorage } from 'hono/context-storage'

export const createContext = (req: Request) => {
const serverContext = {
headers: req.headers,
key: 'your-value',
// db: new DatabaseConnection() // It's also a good idea to store database connections, etc.
export interface Env {
Variables: {
headers: Headers
key: string
// db: DatabaseConnection // It's also a good idea to store database connections, etc.
}

return serverContext
}

const getStore = () => {
const store = context.getStore()
const app = new Hono<Env>()

if (!store) {
throw new Error('No context store found')
}

return store
}

export const getHeaders = () => {
return getStore().headers()
}

// export const db = () => {
// return getStore().db
// }
```

Store the context created in AsyncLocalStorage with Hono.

```ts
// server/index.ts
import { Hono } from 'hono'
import { context, createContext } from './contexts'

const app = new Hono()
app.use(contextStorage())

app.use(async (c, next) => {
const serverContext = createContext(c.req.raw)
c.set('headers', c.req.raw.headers)
c.set('message', 'Hello!')

await context.run(serverContext, async () => {
await next()
})
await next()
})

export default app
```

You can retrieve and process the context stored in AsyncLocalStorage from Remix as follows.
You can retrieve and process the context saved in Hono from Remix as follows:

```ts
// app/routes/_index.tsx
import { getHeaders } from 'server/context' // It can be called anywhere for server-side processing.
import type { Env } from 'server'
import { getContext } from 'hono/context-storage' // It can be called anywhere for server-side processing.
export const loader = () => {
const cookie = getHeaders().get('Cookie')
const cookie = getContext<Env>().headers.get('Cookie')
}
```

Expand Down

0 comments on commit e469093

Please sign in to comment.