The redirect function returns a new Redirect object that can be either returned or thrown from places like a Route's beforeLoad or loader callbacks to trigger redirect to a new location.
The redirect function accepts a single argument, the options to determine the redirect behavior.
import { redirect } from '@tanstack/react-router'
const route = createRoute({
// throwing an internal redirect object using 'to' property
loader: () => {
if (!user) {
throw redirect({
to: '/login',
})
}
},
// throwing an external redirect object using 'href' property
loader: () => {
if (needsExternalAuth) {
throw redirect({
href: 'https://authprovider.com/login',
})
}
},
// or forcing `redirect` to throw itself
loader: () => {
if (!user) {
redirect({
to: '/login',
throw: true,
})
}
},
// ... other route options
})
When using file-based routing with createFileRoute, you can use the Route.redirect method directly. This method automatically sets the from parameter based on the route's path, enabling type-safe relative redirects without manually specifying the origin route:
// In routes/dashboard/settings.tsx
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard/settings')({
beforeLoad: ({ context }) => {
if (!context.user) {
// Relative redirect - automatically knows we're redirecting from '/dashboard/settings'
throw Route.redirect({
to: '../login', // Redirects to '/dashboard/login'
})
}
},
loader: () => {
// Also works in loader
if (needsMigration) {
throw Route.redirect({
to: './migrate', // Redirects to '/dashboard/settings/migrate'
})
}
},
})
For accessing the redirect method outside of the route definition file, you can use getRouteApi:
import { getRouteApi } from '@tanstack/react-router'
const routeApi = getRouteApi('/dashboard/settings')
// In a beforeLoad or loader callback
function checkAuth() {
if (!user) {
// Type-safe redirect with automatic 'from' parameter
throw routeApi.redirect({
to: '../login',
})
}
}
Using Route.redirect or getRouteApi().redirect instead of the standalone redirect function offers several advantages: