Capítulo 51 de 57

Chapter 51: Authenticated Routes

Core Idea

TanStack Router protects routes primarily through the beforeLoad option, which runs before a route (and importantly, before any of its child routes' beforeLoad), making it effective middleware for guarding an entire route subtree by throwing a redirect() or short-circuiting rendering.

Key Concepts

  • beforeLoad as auth middleware: Receives the same arguments as loader and is the recommended place to verify user credentials before a route (and its children) load.
  • Parent-before-child execution order: A route's beforeLoad always runs before any child route's beforeLoad, so guarding a parent route protects the whole subtree beneath it.
  • Redirect-based protection: Throwing redirect({ to: '/login', search: { redirect: location.href } }) inside beforeLoad sends unauthenticated users to a login page, optionally preserving the original destination in a redirect search param for post-login return navigation.
  • isRedirect() helper: Used when catching errors during authentication checks, to distinguish an intentional redirect() throw from a genuine error that should be handled differently.
  • Non-redirect (inline) protection: Instead of navigating away, a route's component can conditionally render a login form in place of <Outlet />, short-circuiting child route rendering without changing the URL.
  • Context-based auth for React: Since hooks can't run in beforeLoad, authentication state derived from React context/hooks should be passed into the router via router.context, set up before <RouterProvider> mounts (see Router Context chapter for the wiring pattern).

Code Examples

if (!isAuthenticated()) {
  throw redirect({
    to: '/login',
    search: { redirect: location.href },
  })
}
  • What it demonstrates: Throwing a redirect() from beforeLoad to gate an unauthenticated user, preserving the intended destination for post-login redirect.

Key Takeaways

  1. Guard a route subtree once, on the shared parent route's beforeLoad, rather than repeating auth checks on every leaf route.
  2. Use isRedirect() when wrapping auth checks in try/catch, to avoid accidentally swallowing or mishandling an intentional redirect throw.
  3. Prefer redirecting to a login route with the original URL captured in search params, enabling a smooth return-to-destination flow after login.
  4. For React-hook-based auth state, bridge it into router context before rendering <RouterProvider>, since beforeLoad cannot call hooks directly.

Connects To

  • Ch 49: Router Context, details the pattern for injecting React-hook-derived state (like auth) into the router via context.
  • Ch 50: Not Found Errors, beforeLoad is the shared hook used for both auth redirects and not-found checks.
  • Concept: redirect() function, the throwable navigation primitive used for auth gating.