H
Hono•4w ago
Carere

Are middleware singleton like in ElysiaJS ?

Hello, Just wondering if middleware were singleton like in Elysia ? I have a middleware which is my dependency container, and I need to apply a .use(container) on each route which needs to access the container. Should I add a check in my code to not add my variables to context if it already been added ? Or does Hono do this for me with a specific option ? Thx for your answers 🙂
3 Replies
ambergristle
ambergristle•4w ago
i haven't worked w Elysia, but i'm a little surprised to hear that every middleware is a singleton in general, Hono middleware is not, though the implementations are quite minimal + clear, so you can always check the source for a specific middleware but in some cases you could instantiate your middleware in a singleton-like way
const middlewareInstance = initMiddleware({ /** config */ })

const app = new Hono()
.use(middlewareInstance)

// instead of
const app = new Hono()
.use(initMiddleware({ /** config */ }))
const middlewareInstance = initMiddleware({ /** config */ })

const app = new Hono()
.use(middlewareInstance)

// instead of
const app = new Hono()
.use(initMiddleware({ /** config */ }))
an easier approach might be to just use the middleware once, just higher up the tree
const app = new Hono()
.use(container)
.route('/a', /** */)
.route('/b', /** */)
.route('/c', /** */)
const app = new Hono()
.use(container)
.route('/a', /** */)
.route('/b', /** */)
.route('/c', /** */)
this will apply the middleware to all following routes you can/should use generic types to let Hono know how you modify Context via middleware but, at this time those types aren't shared between middleware (or an implementation like the above) so you'll need to do something like:
const aRouter = new Hono<ParentMiddlewareTyping>()
const aRouter = new Hono<ParentMiddlewareTyping>()
can you share a bit more about what you're trying to accomplish
Carere
CarereOP•4w ago
Thx for your exhaustive answer 🙂 I actually just creating a web api for my project and I wanted to initialize a container dependency at the beginning of my server. So I think I'm gonna declare it at the top of my Api and I'm gonna pass the generic to each instance of route 😉
ambergristle
ambergristle•4w ago
word. that makes sense to me i've done something like that for rate limiting; works great! happy to help!

Did you find this page helpful?