How to listen for the Hono shutdown event in middleware ? #4486
|
I create a Redis middleware like this export const cacheMiddleware = (opts?: RedisOptions) => {
const cache = new Redis(opts)
// How to close redis when Hono stop ?
// await cache.close()
return createMiddleware(async (c, next) => {
c.set('cache', cache)
await next()
})
} |
Replies: 1 comment 1 reply
|
There's no "Hono shutdown event" to hook, and that's by design — Hono is just a request handler, it doesn't own the server or the process lifecycle. Middleware runs per request, so it's the wrong place to do one-time teardown. The cleanup belongs where your resource is created (once, in the closure — which you're already doing correctly) and runs at the runtime level on shutdown. Keep the client in the closure as you have it, but expose it so you can close it from a signal handler: export function cacheMiddleware(opts?: RedisOptions) {
const cache = new Redis(opts) // created once, when middleware is registered
const mw = createMiddleware(async (c, next) => {
c.set('cache', cache)
await next()
})
return { middleware: mw, close: () => cache.quit() }
}Then wire the teardown to the runtime. On Node ( const { middleware, close } = cacheMiddleware()
app.use(middleware)
const server = serve({ fetch: app.fetch, port: 3000 })
function shutdown() {
server.close(async () => { // stop accepting connections first
await close() // then close Redis
process.exit(0)
})
}
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)I tested this end to end on Node 26 with It differs by runtime, since "shutdown" is a runtime concept, not a Hono one:
So: single client in the closure (✅ what you have), expose a |
There's no "Hono shutdown event" to hook, and that's by design — Hono is just a request handler, it doesn't own the server or the process lifecycle. Middleware runs per request, so it's the wrong place to do one-time teardown. The cleanup belongs where your resource is created (once, in the closure — which you're already doing correctly) and runs at the runtime level on shutdown.
Keep the client in the closure as you have it, but expose it so you can close it from a signal handler: