Redirect unauthenticated users from beforeLoad
Protecting authenticated routes
TanStack · Function
TanStack Router's redirect function creates a Redirect object that can be returned or thrown to navigate from route callbacks. The throw option controls whether the object is thrown immediately.
TanStack Router's redirect function creates a Redirect object for changing location. Return it or throw it from callbacks such as a route's beforeLoad or loader; setting throw to true makes the function throw the object immediately.
redirect(options)| Name | Type | Description |
|---|---|---|
opts | Redirect | Options controlling the redirect behavior, including navigation properties and the optional throw flag. |
A Redirect object; it is thrown when the options object's throw property is true.
import { redirect } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard')({
beforeLoad: ({ context }) => {
if (!context.auth.user) {
throw redirect({ to: '/login' })
}
},
})Throw the redirect from a route lifecycle callback to navigate unauthenticated users to the login route.
Protecting authenticated routes
Loading route data
File-based routing
redirect accepts one options object and returns a Redirect object by default. It can be returned or thrown from route beforeLoad and loader callbacks to trigger navigation.
Follow-up: How can a caller force throwing behavior? Set throw: true in the options; otherwise the object is returned.
The function is useful in route lifecycle callbacks, especially beforeLoad and loader. Throwing or returning the resulting Redirect causes TanStack Router to navigate to the target location.
Follow-up: Why might beforeLoad be preferable for authentication? It runs during route loading, allowing the redirect decision before the protected route finishes loading.
File-based routes can use Route.redirect directly. That helper automatically supplies the route's from value, which enables type-safe relative redirects without manually providing the origin route.
Follow-up: When is an explicit from value unnecessary? When using the file-based Route.redirect helper, because it derives from from the route path.
RedirectRoute.redirectbeforeLoadloaderNavigateOptions