Replies: 3 comments
-
Hi @pdlug, I've been playing around with
declare module "hono" {
interface ContextVariableMap {
user?: User;
}
}
function getUser(c: Context<any, any, {}>): User {
const { user } = c.var
if (!user) {
throw new HTTPException(401, { message: 'Not signed in' })
}
return c.get('user')
} see https://hono.dev/docs/api/exception This way you can ensure the code executed beneath the Hope that helps! |
Beta Was this translation helpful? Give feedback.
-
I've been struggling with this exact same usecase too. I have tried structuring my custom authentication middleware to match @nmcdaines I've ended up using your approach but would love for someone to shed light on how to get this working in the same way the included middlewares conditionally apply typesafe values to the context. |
Beta Was this translation helpful? Give feedback.
-
Please refer to my reply in another discussion. |
Beta Was this translation helpful? Give feedback.
-
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 makeuser
optional then in every handler that uses my middleware I need a guardif (!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?
Beta Was this translation helpful? Give feedback.
All reactions