From e469093f9efd3957229ab0a89f6d7ad0c31ea569 Mon Sep 17 00:00:00 2001 From: chimame Date: Mon, 9 Dec 2024 21:18:47 +0900 Subject: [PATCH] Change AsyncLocalStorage to an example of using Context Storage Middleware --- README.md | 62 ++++++++++++++++--------------------------------------- 1 file changed, 18 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index c73567b..35979b6 100644 --- a/README.md +++ b/README.md @@ -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>() +// 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() - 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().headers.get('Cookie') } ```