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
correct-apricot•14mo 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.wise-whiteOP•14mo 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'})
correct-apricot•14mo ago
Yup that should do it.
wise-whiteOP•14mo ago
awesome, thanks for help