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 a redirect object
  loader: () => {
    if (!user) {
      throw redirect({
        to: '/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 a redirect object
  loader: () => {
    if (!user) {
      throw redirect({
        to: '/login',
      })
    }
  },
  // or forcing `redirect` to throw itself
  loader: () => {
    if (!user) {
      redirect({
        to: '/login',
        throw: true,
      })
    }
  },
  // ... other route options
})
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.