Type safety for middleware that sets context variables
I have an authentication middleware which ensures the user is logged in and adds the
user
to the context if they are. My middleware adds the type of this context variable per the docs:
The problem is, all handlers see c.get('user')
as being present even if they don't use the middleware. If I make user
optional then in every handler that uses my middleware I need a guard if (!user) return c.json(...)
which is redundant because the middleware is already guaranteeing that the context variable is set.
Is there any way around this?6 Replies
Hello
If you do it like this, you don’t need to use the declare module “hono”
Just use your middleware on the route and it will have access to it
Notice you don’t provide a type when you create the hono instance
If you do it like here, and use the middleware in every route
Then. You need to pass the type and do the declare module
Sorry for the print screens but it is easier since I’m on the phone
Thanks that really helped!
Sorry for hijacking this thread, but I'm facing a similar issue and the above solution doesn't seem to work for me.
This returns error
Type 'BlankEnv' is not assignable to type 'Env'.
when using echoMiddleware in my get handler. It seems like app
defaults to BlankEnv and does not work with middlewares with custom variables. Defining Variables
when initializing Hono()
fixes the issue but just like OP, I do not want all other handlers to get access to it.