Paul Dlug
Paul Dlug
Explore posts from servers
HHono
Created by Paul Dlug on 8/10/2024 in #help
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:
declare module "hono" {
interface ContextVariableMap {
user: User;
}
}
declare module "hono" {
interface ContextVariableMap {
user: User;
}
}
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?
11 replies