Beginner: infer context type
Hey everyone, this might seem like a simple question but I couldn't find an answer online for it.
In the following snipet how could I change the type of session from (Session | null) to (Session) since I have a middleware that checks if it's null before the controller ?
here is the code:
13 Replies
hi, i'm not really sure that's relevant but I think I did something a bit similar for handling ory authentication / registration:
let me know if that helps!
Thanks for the help, but unfortunatly that doesn't really solve my issue as your type is marked as
sdk.Identityand can't you type your session in
Ctx as Session?
what is the retun type of await validateSession(token)?it would be
Session | null as it's a global middleware, and the token could be invalidOK so from my understanding, you're applying a global middleware to all your routes, but want to ensure authentification only for some of them (hence the null support)? Or for all routes?
From my basic understanding of Hono, I think the envs you provide as a type to your Hono are designed in case you wish to pass extra args between middlewares / handlers / routes. For me, you could imagine using a
Session type and rather than checking the c.var.session in your post route just do something like:
and in your routes c.get("session") would never be nullok nice that makes sense, thanks 🙂
and if you want to have some routes that don't need authentication, just specify a restricting path for the protected ones or provide the middleware explicitly to each route
true
shame that hono isn't cascading the types to the other routes / middleware though
but that works as well
it does, sort of
only inline handlers + middleware can infer the types though; otherwise they need to be generically typed
i don't think you get anything out of the
Session | null type, unless there are optionally-authed routes or something, but you can definitely use inference to narrow the typeThanks @ambergristle this makes a lot more sense
it's worth taking a look at these:
- https://hono.dev/docs/guides/middleware
- https://hono.dev/docs/guides/best-practices
- https://hono.dev/docs/helpers/factory
i also wrote this article about (validation) middleware in hono, which touches some on how typing works: https://dev.to/fiberplane/hacking-hono-the-ins-and-outs-of-validation-middleware-2jea
awesome, thanks for that
np