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: Add example of using AsyncLocalStorage to README #47

Merged
Changes from 3 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
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -335,6 +335,52 @@ 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/index.ts
import { Hono } from 'hono'
import { contextStorage } from 'hono/context-storage'

export interface Env {
Variables: {
headers: Headers
key: string
// db: DatabaseConnection // It's also a good idea to store database connections, etc.
}
}

const app = new Hono<Env>()

app.use(contextStorage())

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

await next()
})

export default app
```

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

```ts
// app/routes/_index.tsx
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 = getContext<Env>().var.headers.get('Cookie')
yusukebe marked this conversation as resolved.
Show resolved Hide resolved
const message = getContext<Env>().var.message
...
}
```

## Auth middleware for Remix routes

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:
Expand Down