Hono v4.6.0 is now available!
One of the highlights of this release is the Context Storage Middleware. Let's introduce it.
Context Storage Middleware
Many users may have been waiting for this feature. The Context Storage Middleware uses AsyncLocalStorage
to allow handling of the current Context object even outside of handlers.
For example, let’s define a Hono app with a variable message: string
.
type Env = {
Variables: {
message: string
}
}
const app = new Hono<Env>()
To enable Context Storage Middleware, register contextStorage()
as middleware at the top and set the message
value.
import { contextStorage } from 'hono/context-storage'
//...
app.use(contextStorage())
app.use(async (c, next) => {
c.set('message', 'Hello!')
await next()
})
getContext()
returns the current Context object, allowing you to get the value of the message
variable outside the handler.
import { getContext } from 'hono/context-storage'
app.get('/', (c) => {
return c.text(getMessage())
})
// Access the variable outside the handler.
const getMessage = () => {
return getContext<Env>().var.message
}
In the case of Cloudflare Workers, you can also access the Bindings
outside the handler by using this middleware.
type Env = {
Bindings: {
KV: KVNamespace
}
}
const app = new Hono<Env>()
app.use(contextStorage())
const setKV = (value: string) => {
return getContext<Env>().env.KV.put('key', value)
}
Thanks @marceloverdijk !
New features
- feat(secureHeader): add Permissions-Policy header to secure headers middleware #3314
- feat(cloudflare-pages): enable
c.env.eventContext
in handleMiddleware #3332 - feat(websocket): Add generics type to
WSContext
#3337 - feat(jsx-renderer): set
Content-Encoding
whenstream
is true #3355 - feat(serveStatic): add
precompressed
option #3366 - feat(helper/streaming): Support
Promise<string>
or (async)JSX.Element
instreamSSE
#3344 - feat(context): make fetch Response headers mutable #3318
- feat(serve-static): add
onFound
option #3396 - feat(basic-auth): added custom response message option #3371
- feat(bearer-auth): added custom response message options #3372
Other changes
- chore(jsx-renderer): fix typo in JSDoc by @taga3s in #3378
- chore(deno): use the latest jsr libraries for testing by @ryuapp in #3375
- fix(secure-headers): optimize getPermissionsPolicyDirectives function by @kbkn3 in #3398
- fix(bearer-auth): typo by @yusukebe in #3404
New Contributors
- @kbkn3 made their first contribution in #3314
- @hayatosc made their first contribution in #3337
- @inetol made their first contribution in #3366
Full Changelog: v4.5.11...v4.6.0