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•17mo ago
did you have a look at the documentation?
https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes
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-goldOP•17mo ago
yes
but he use local storage
is sync
If possible, do something in the beforeLoad of the router
statutory-emerald•17mo ago
beforeLoad can be async
like-goldOP•17mo ago
The problem is when i have a 401, the error component is showing
i have this
__root.tsx
file
statutory-emerald•17mo ago
can you please provide a minimal complete example, e.g .by forking one of the existing examples on stackblitz?
like-goldOP•17mo 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