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(middleware): add instructions for extending context #460

Merged
merged 1 commit into from
Aug 24, 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
docs(middleware): add instructions for extending context
  • Loading branch information
iveshenry18 authored Aug 23, 2024
commit e61236d1d6157b59aa375ee551f638bc7b86d4b6
21 changes: 21 additions & 0 deletions docs/guides/middleware.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,27 @@ app.use('*', async (c, next) => {
})
```

### Extending the Context in Middleware

To extend the context inside middleware, use `c.set`. You can make this type-safe by passing a `{ Variables: { yourVariable: YourVariableType } }` generic argument to the `createMiddleware` function.

```ts
import { createMiddleware } from 'hono/factory'

const echoMiddleware = createMiddleware<{
Variables: {
echo: (str: string) => string
}
}>(async (c, next) => {
c.set('echo', (str) => str)
await next()
})

app.get('/echo', echoMiddleware, (c) => {
return c.text(c.var.echo('Hello!'))
})
```

## Third-party Middleware

Built-in middleware does not depend on external modules, but third-party middleware can depend on third-party libraries.
Expand Down