T
TanStack17mo ago
like-gold

Protected routes with query

I have my API which has an auth system which uses sessions via cookies. The problem is that to check if the user is logged in, I make a request to /auth/me. I would like on my router to make a request to this endpoint (API) to check if the user is connected or not. I want to know if it is possible to do this? If not, what is the best way to check if the user is logged in? FYI, I use Tanstack Query to do my queries.
6 Replies
statutory-emerald
statutory-emerald17mo ago
Authenticated Routes | TanStack Router React Docs
Authentication is an extremely common requirement for web applications. In this guide, we'll walk through how to use TanStack Router to build protected routes, and how to redirect users to login if they try to access them. The route.beforeLoad Option
like-gold
like-goldOP17mo ago
yes but he use local storage is sync If possible, do something in the beforeLoad of the router
statutory-emerald
statutory-emerald17mo ago
beforeLoad can be async
like-gold
like-goldOP17mo ago
The problem is when i have a 401, the error component is showing i have this __root.tsx file
const options = queryOptions({
queryKey: ['current-user'],
queryFn: fetchCurrentUser,
select: res => res.data,
retry: false
})

export const Route = createRootRouteWithContext<{
queryClient: QueryClient
isLoggedIn: boolean | null
}>()({
component: Root,
beforeLoad: ({ context: { queryClient } }) =>
queryClient.ensureQueryData(options)
})

function Root(): JSX.Element {
return (
<>
<Outlet />

<TanStackRouterDevtools />
<ReactQueryDevtools />
</>
)
}
const options = queryOptions({
queryKey: ['current-user'],
queryFn: fetchCurrentUser,
select: res => res.data,
retry: false
})

export const Route = createRootRouteWithContext<{
queryClient: QueryClient
isLoggedIn: boolean | null
}>()({
component: Root,
beforeLoad: ({ context: { queryClient } }) =>
queryClient.ensureQueryData(options)
})

function Root(): JSX.Element {
return (
<>
<Outlet />

<TanStackRouterDevtools />
<ReactQueryDevtools />
</>
)
}
statutory-emerald
statutory-emerald17mo ago
can you please provide a minimal complete example, e.g .by forking one of the existing examples on stackblitz?
like-gold
like-goldOP17mo ago
I don't know if you see what I want to do I want in the beforeLoad to fetch the logged in user (or not) and store it in a store. Currently I'm using zustand, but it needs to be in a component to use actions. Like this my isLoggedIn context in my tanstack router will be connected to the isLoggedIn variable in my store, and I could use it to protect routes

Did you find this page helpful?