Capítulo 51 de 57
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.
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.beforeLoad always runs before any child route's beforeLoad, so guarding a parent route protects the whole subtree beneath it.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.<Outlet />, short-circuiting child route rendering without changing the URL.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).if (!isAuthenticated()) {
throw redirect({
to: '/login',
search: { redirect: location.href },
})
}
redirect() from beforeLoad to gate an unauthenticated user, preserving the intended destination for post-login redirect.beforeLoad, rather than repeating auth checks on every leaf route.isRedirect() when wrapping auth checks in try/catch, to avoid accidentally swallowing or mishandling an intentional redirect throw.<RouterProvider>, since beforeLoad cannot call hooks directly.beforeLoad is the shared hook used for both auth redirects and not-found checks.redirect() function, the throwable navigation primitive used for auth gating.