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
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
an easier approach might be to just use the middleware once, just higher up the tree
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:
can you share a bit more about what you're trying to accomplishThx 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 😉
word. that makes sense to me
i've done something like that for rate limiting; works great!
happy to help!