Is it possible to narrow auth type on authenticated routes?
Hi,
for the sake of simplicity, let's talk about authenticated routes example from the documentation: https://tanstack.com/router/latest/docs/framework/react/examples/authenticated-routes
If you look at
_auth.dashboard.tsx, auth.user is of type string | null. I would like it to be just string, since I assume the user to be valid at this point.
If I should not do this and instead redirect to login on invalid user in each route, what would be the reasons for that?React TanStack Router Authenticated Routes Example | TanStack Route...
An example showing how to implement Authenticated Routes in React using TanStack Router.
4 Replies
equal-aqua•17mo ago
In the
beforeLoad of your _auth.tsx file, return an object with the user and its type being narrowed.
Then all children of _auth should have that returned object's user type narrowed.solid-orangeOP•17mo ago
since I'm new to this, could you confirm that this is the correct way:
in
_auth.tsx I change the condition to if (context.auth.user === null) to narrow the type.
After the if I add return {username: context.auth.user}.
then in _auth.dashboard.tsx I access it via const {username} = useRouteContext({from: '/_auth'})equal-aqua•17mo ago
Yup that should do it.
solid-orangeOP•17mo ago
awesome, thanks for help