Questions about router context in authenticated routes #4763
Unanswered
happenslol
asked this question in
Q&A
Replies: 1 comment 3 replies
-
no you cannot remove from route context, only add. |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hey, I have a question about route context, especially in the context of authenticated/protected routes.
I have an auth provider wrapping my entire app, which ensures that we know whether the user is authenticated or not. According to the docs, I pass this into the router context so I can check it in
beforeLoad
.Now, here are my questions:
Why iscontext.auth
nullable? I defined the root route ascreateRootRouteWithContext<{ auth: AuthContext }>()
, and the context is required oncreateRouter
. It feels like that should be non-nullable on thebeforeLoad
argument as well.<RouterProvider />
react to changes in thecontext
prop? The auth provider must wrap the router provider so it can pass the context - which means I can't get the router inside the auth provider. It seems I would have to create a new hook inside both the router and auth provider that listens to auth changes and then invalidates the router based on that. What's the best practice here?It would be great if I could refine the context type for a specific route and all its children. That would allow me to make a non-nullable user field available to all authenticated routes. I couldn't devise a way to do this with the docs, did I miss something?Edit:
First question solved. I defined my context as
type AuthContext = { ... } | null
, so I can default-init it withnull
and then do a non-null check inuseAuthContext
. Apparently, when all sub-values of the router context are optional, the context itself becomes optional as well. A bit unintuitive, I would have expected that only if I defined the context as{ auth?: AuthContext }
, and not also{ auth: AuthContext | null }
.This issue is solved by moving the
| null
to the context create call instead.I've also figured out the third question. Apparently I'm blind and we can just return something else from
beforeLoad
.It seems I can only add to the context - can I remove something as well? It would be great to remove the
login
function in authenticated routes, for example.It would also be nice to have helper types to write context extractor hooks. I now have this:
which is... unwieldy, to say the least.
Beta Was this translation helpful? Give feedback.
All reactions