Skip to content

Instantly share code, notes, and snippets.

@mjackson
Last active November 12, 2023 07:32
Show Gist options
  • Save mjackson/b5748add2795ce7448a366ae8f8ae3bb to your computer and use it in GitHub Desktop.
Save mjackson/b5748add2795ce7448a366ae8f8ae3bb to your computer and use it in GitHub Desktop.
Notes on handling redirects in React Router v6, including a detailed explanation of how this improves on what we used to do in v4/5

Redirects in React Router v6

An important part of "routing" is handling redirects. Redirects usually happen when you want to preserve an old link and send all the traffic bound for that destination to some new URL so you don't end up with broken links.

The way we recommend handling redirects has changed in React Router v6. This document explains why.

Background

In React Router v4/5 (they have the same API, you can read about why we had to bump the major version here) we had a <Redirect> component that you could use to tell the router when to automatically redirect to another URL. You might have used it like this:

import { Switch, Route, Redirect } from "react-router-dom";

function App() {
  return (
    <Switch>
      <Route path="/home">
        <HomePage />
      </Route>
      <Redirect from="/" to="/home" />
    </Switch>
  );
}

In React Router v4/5, when the user lands at the / URL in the app above, they are automatically redirected to /home.

There are two common environments in which React Router usually runs:

  • In the browser
  • On the server using React's node.js API

In the browser a <Redirect> is simply a history.replaceState() on the initial render. The idea is that when the page loads, if you're at the wrong URL, just change it and rerender so you can see the right page. This gets you to the right page, but also has some issues as we'll see later.

On the server you handle redirects by passing an object to <StaticRouter context> when you render. Then, you check context.url and context.status after the render to see if a <Redirect> was rendered somewhere in the tree. This generally works fairly well, except you have to invoke ReactDOMServer.renderToString(...) just to know if you need to redirect, which is less than ideal.

Problems

As mentioned above, there are a few problems with our redirect strategy in React Router v4/5, namely:

  • "Redirecting" in the browser isn't really redirecting. Your server still served up a valid HTML page with a 200 status code at the URL originally requested by the client. If that client was a search engine crawler, it got a valid HTML page and assumes it should index the page. It doesn't know anything about the redirect because the page was served with a 200 OK status code. This hurts your SEO for that page.
  • Invoking ReactDOMServer.renderToString() on the server just to know if you need to redirect or not wastes precious resources and time. Redirects can always be known ahead of time. You shouldn't need to render to know if you need to redirect or not.

So we are rethinking our redirect strategy in React Router v6 to avoid these problems.

Handling Redirects in React Router v6

Our recommendation for redirecting in React Router v6 really doesn't have much to do with React or React Router at all. It is simply this: if you need to redirect, do it on the server before you render any React and send the right status code. That's it.

If you do this, you'll get:

  • better SEO for redirected URLs and
  • faster responses from your web server

To handle the situation above, your server code might look something like this (using the Express API):

import * as React from "react";
import * as ReactDOMServer from "react-dom/server";
import { StaticRouter } from "react-router-dom/server";

import App from "./App";

function handleExpressRequest(req, res) {
  // Handle redirects *before* you render and save yourself some time.
  // Bonus: Send a HTTP 302 Found status code so crawlers don't index
  // this page!
  if (req.url === "/") {
    return res.redirect("/home");
  }

  // If there aren't any redirects to process, go ahead and render...
  let html = ReactDOMServer.renderToString(
    <StaticRouter location={req.url}>
      <App />
    </StaticRouter>
  );

  // ...and send a HTTP 200 OK status code so crawlers index the page.
  res.end(html);
}

This will ensure that both:

  • search engine crawlers can see the redirect and avoid indexing the redirected page and
  • you don't waste any more resources server rendering than you have to

Configuring Static Hosting Providers

Many static hosting providers give you an easy way to configure redirects so you can still get good SEO even on a static site with no server. See the docs on various providers below:

On static hosting providers that don't provide a way to do redirects on the server (e.g. GitHub Pages), you can still improve SEO by serving a page with the the redirect encoded in the page's metadata, like this:

<!doctype html>
<title>Redirecting to https://example.com/home</title>
<meta http-equiv="refresh" content="0; URL=https://example.com/home">
<link rel="canonical" href="https://example.com/home">

The <meta> tag tells the browser where to go, and the <link> tag tells crawlers to use that page as the "canonical" representation for that page, which allows you to consolidate duplicate URLs for Googlebot.

Not Server Rendering

If you aren't server rendering your app you can still redirect on the initial render in the client like this:

import { Routes, Route, Navigate } from "react-router-dom";

function App() {
  return (
    <Routes>
      <Route path="/home" element={<Home />} />
      <Route path="/" element={<Navigate replace to="/home" />} />
    </Routes>
  );
}

In the above example, when someone visits /, they will automatically be redirected to /home, same as before.

Please note however that this won't work when server rendering because the navigation happens in a React.useEffect().

Notes on the <Navigate> API

The new <Navigate> element in v6 works like a declarative version of the useNavigate() hook. It's particularly handy in situations where you need a React element to declare your navigation intent, like <Route element>. It also replaces any uses that you had for a <Redirect> element in v5 outside of a <Switch>.

The <Navigate replace> prop tells the router to use history.replaceState() when updating the URL so the / entry won't end up in the history stack. This means that when someone clicks the back button, they'll end up at the page they were at before they navigated to /.

Get Started Upgrading Today

You can prepare your React Router v5 app for v6 by replacing any <Redirect> elements you may be rendering inside a <Switch> with custom redirect logic in your server's request handler.

Then, you can stop using the <StaticRouter context> API and forget about checking the context object after rendering because you know that all of your redirects have already been taken care of.

If you want to redirect client-side, move your <Redirect> into a <Route render> prop.

// Change this:
<Switch>
  <Redirect from="about" to="about-us" />
</Switch>

// to this:
<Switch>
  <Route path="about" render={() => <Redirect to="about-us" />} />
</Switch>

Normal <Redirect> elements that are not inside a <Switch> are ok to remain. They will become <Navigate> elements in v6.

@shrekuu
Copy link

shrekuu commented May 30, 2022

What should we do with conditional redirects? For example new user need to be redirected to onboarding wizard

I have something similar.

import { Navigate, RouteObject, useRoutes } from 'react-router-dom'
import Index from '@/pages/Index'
import Products from '@/pages/Products'
import { IAppStore, useAppStore } from './store'

export default function Routes() {
  const stores = useAppStore((state: IAppStore) => state.stores)
  const activeStoreId = stores.find(e => e.active)?.id

  const routes: RouteObject[] = [
    // Here, if activeStoreId exists, redirect to Products Page.
    { path: '/', element: activeStoreId ? <Navigate to={`${activeStoreId}/products`} /> : <Index /> },
    { path: '/:storeId/products', element: <Products /> },
  ]

  return useRoutes(routes)
}

@RubenZx
Copy link

RubenZx commented Oct 14, 2022

What about dynamic routes on redirect? I mean, before v6 we had the following:

<Redirect from="/original/route/:something" to="/new/route/:something" /> 

But now with the Navigate solution this doesn't work:

<Route
  path="/original/route/:something"
  element={<Navigate replace to="/new/route/:something" />}
/>

If you go to /original/route/example it redirects you to /new/route/:something instead of /new/route/example. I've been searching in the documentation but I cannot find anything about this.

@nathanschwarz
Copy link

nathanschwarz commented Oct 17, 2022

I've used a nice solution since v4 to avoid SEO issues for SSR redirections :

// for both server && client : require extra config to replace process in the client bundle
const IS_SSR = process?.env === undefined

// on the server
let serverContext = { redirection: null }
const tree = <App context={serverContext} />
if (serverContext.redirect !== null) {
    return res.redirect(serverContext.redirection.url, serverContext.redirection.code)
}

// in a nested component
function MyComponent(props) {
   const redirect: boolean = shouldRedirect() // some logic here
   if (redirect) {
        if (IS_SSR) {
             // throwing an error will avoid rendering the rest of the tree
             const err = new Error('redirect', { reason:  'someUrl' })
             err.code = 301 // some redirection code
             throw err
         }
        return <Navigate to='someUrl' />
   }
}

// in your error component
function ErrorCatcher({ serverContext }) {
    //...your logic here
    if (error.message === 'redirect') {
         serverContext = { redirection: { url: error.reason, code: error.code }}
         return null
    }
}

Hope that can help some.

@jonDufty
Copy link

Plus we use many dynamic redirects from layout-route paths to a first-child, which differs because the sitemap is dynamic, based on user-rights and user preferences. I had to create a wrapper around <Navigate> with more precise logic to fix some infinite loops when redirecting to nested children, but RR6 provides the tools needed to make it work

@allpro do you mind sharing how you went about doing this. We're looking at a similar use case

@nirmaoz
Copy link

nirmaoz commented Oct 26, 2022

@RubenZx @jonDufty and anyone else who needs a solution for <Navigate> with dynamic segments,
I've just published this package that solves the issue. It exports a <Redirect> component that uses <Navigate replace> internally.
It supports dynamic segments like /something/:id.
https://www.npmjs.com/package/react-router6-redirect

@hichemfantar
Copy link

Is there a solution for the flicker issue mentioned in this issue when using the redirect element?

@etipton
Copy link

etipton commented Mar 24, 2023

@RubenZx @jonDufty and anyone else who needs a solution for <Navigate> with dynamic segments, I've just published this package that solves the issue. It exports a <Redirect> component that uses <Navigate replace> internally. It supports dynamic segments like /something/:id. https://www.npmjs.com/package/react-router6-redirect

@nirmaoz great stuff here, thank you!

@CookieBOY
Copy link

CookieBOY commented Aug 27, 2023

Is there any solution that we can redirect the nested routes? for example:

const routes = [
     {
    path: 'nested-routes',
    element: <NestedRoutes/>,
    children: [
      {
        path: 'nested1',
        element: <Nested1/>
      },
      {
        path: 'nested2',
        element: <Nested2/>
      },
    ]
  },
]

when I visit localhost:3000/nested-routes, actually, I want to visit localhost:3000/nested-routes/nested1.How can I achieve this problem. Thanks

Even i was looking for the solution for this but after some research I came up with a solution
You can have a parent component similar to this

import { useNavigate, Outlet } from "react-router-dom";
import React, { useEffect } from "react";

const NestedRoutes = () => {
    const navigate = useNavigate()
    const location = useLocation()

    useEffect(() => {
    if (location.pathname === '/nested-routes')
      navigate('/nested-routes/nested1')
  }, [navigate, location.pathname])

return ( <Outlet /> )
}

@kouroshey
Copy link

Thank u. It was very helpful for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment