TanStackT
TanStack7mo ago
11 replies
wispy-yellow

Idiomatic ways to handle route-guarding

This doc led me to using router contexts to be able to pass authentication context to the router https://tanstack.com/router/v1/docs/framework/react/guide/authenticated-routes#authentication-using-react-contexthooks

However I'm running into an issue. Here's my route:

export const Route = createFileRoute("/dashboard")({
  beforeLoad: ({ context, location }) => {
    // Check authentication using context
    console.log("[Dashboard Route Guard] Checking authentication:", {
      path: location.pathname,
      isAuthenticated: context.auth.isAuthenticated,
      hasUser: !!context.auth.user,
      userEmail: context.auth.user?.email,
      hasJWT: !!context.auth.jwt,
      jwtPreview: context.auth.jwt
        ? `${context.auth.jwt.substring(0, 20)}...`
        : null,
      context,
    });

    if (!context.auth.isAuthenticated || !context.auth.jwt) {
      console.log(
        "[Dashboard Route Guard] Not authenticated, redirecting to signin",
      );
      // eslint-disable-next-line @typescript-eslint/only-throw-error
      throw redirect({
        to: "/signin",
        search: {
          redirect: location.href,
        },
      });
    }


On the server, I see:

[web] [Dashboard Route Guard] Checking authentication: {
[web]   path: '/dashboard',
[web]   isAuthenticated: false,
[web]   hasUser: false,
[web]   userEmail: undefined,
[web]   hasJWT: false,
[web]   jwtPreview: null,
[web]   context: {
[web]     queryClient: QueryClient {},
[web]     auth: {
[web]       isAuthenticated: false,
[web]       user: null,
[web]       jwt: null,
[web]       authFlow: 'logged-out'
[web]     }
[web]   }
[web] }
[web] [Dashboard Route Guard] Not authenticated, redirecting to signin
[web] [Signin Route] Context: {
[web]   queryClient: QueryClient {},
[web]   auth: {
[web]     isAuthenticated: false,
[web]     user: null,
[web]     jwt: null,
[web]     authFlow: 'logged-out'
[web]   }
[web] }
[web] [AppWithAuth] Waiting for store hydration...
[web] [AppWithAuth] Waiting for store hydration...
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?