#Is it possible to narrow auth type on authenticated routes?

4 messages · Page 1 of 1 (latest)

brisk schooner
#

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?

An example showing how to implement Authenticated Routes in React using TanStack Router.

jolly trout
#

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.

brisk schooner
#

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'})

jolly trout
#

Yup that should do it.