Framework
Version

redirect function

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.

redirect options

The redirect function accepts a single argument, the options to determine the redirect behavior.

redirect returns

  • If the throw property is true in the options object, the Redirect object will be thrown from within the function call.
  • If the throw property is false | undefined in the options object, the Redirect object will be returned.

Examples

tsx
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
})
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
})
Our Partners
Clerk
Netlify
Neon
Convex
Sentry
Vercel
Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.

Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.