TanStackT
TanStack12mo ago
135 replies
popular-magenta

authenticated routes

I am implementing authenticated routes and was following the guide in https://tanstack.com/router/v1/docs/framework/react/guide/authenticated-routes#authentication-using-react-contexthooks where it talks about authenticated routes for auth state stored in a Context. It all makes sense but I'm struggling with one thing -

My setup
My react Context gets the state for whether the user is authenticated or not by making an api call to
/user
and if the response is valid and the user details are fetched successfully, it stores that state in the context as
user
. This is the state I am using to validate whether the user is logged in or not.

Question
Given my auth state depends on the user state that is going to be fetched, I don't want the check in
beforeLoad
to happen before that fetch and setting of state is complete. My current code is as follows but even if the user is logged in, it goes to login.

export const Route = createFileRoute('/_authenticated')({
  beforeLoad: ({ context, location }) => {
    if (!context.user) {
      throw redirect({
        to: '/login',
        search: {
          redirect: location.href,
        },
      })
    }
  },
})


The logic of the behavior makes sense but what is the recommended way to handle the
isLoading
state in such a setup?
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 th...
Authenticated Routes | TanStack Router React Docs
Was this page helpful?