Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 50 ยท Declarative Routing Basics

Redirects with Navigate

Redirect old URLs, index routes and logged-out users with the Navigate component, understand push versus replace, keep splats, and avoid redirect loops.

Websites change. A page moves from /old-blog to /blog, a section gets a default tab, a logged-out visitor must be sent to a login page. In every one of these cases the right answer is a redirect: when the app reaches URL A, it immediately continues to URL B.

React Router gives you the <Navigate> component for this. You render it like any other element, and when it appears on screen it moves the user to another location. In this lesson you will use it for old URLs and index routes, learn why replace matters for the back button, keep the rest of a URL when you redirect, and see how a redirect loop happens and how to spot one. Moving the user from an event handler (a button click, a form submit) is a different tool, covered in useNavigate and Imperative Navigation.

The Navigate component

<Navigate to="/blog" replace /> renders nothing. When it mounts, React Router changes the location (it does this in an effect, so rendering stays pure) and the router renders whatever route now matches. This is real React Router code (read-only):

JSX
// App.jsx - React Router (read-only)
import { Routes, Route, Navigate } from 'react-router';

export default function App() {
  return (
    <Routes>
      <Route path="/" element={<Home />} />
      <Route path="blog" element={<Blog />} />
      <Route path="old-blog" element={<Navigate to="/blog" replace />} />
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

The props you will use:

Prop Meaning
to Where to go: a string such as "/blog", or an object { pathname, search, hash }.
replace If present, replace the current history entry instead of adding a new one.
state Any serializable value to attach to the new location (see useLocation and Navigation State).
relative "route" (the default) or "path"; the same option as on links.

Real library or stand-in? The code blocks above are the real API. The live examples use a small hand-written router built on React and location.hash (the sandboxed preview has no real History API). The stand-in Navigate does the same job in a simpler way: it calls location.replace('#/path') in an effect. Outside this lesson you would use the real component.

Redirecting old URLs

Try each link. /docs jumps to /docs/intro, /old-docs/setup keeps the setup part of the URL because the OldDocs component reads the splat and builds the new address from it, and /legacy makes two hops (/legacy to /docs to /docs/intro), which the log records. A chain of redirects works but is slower and harder to maintain: point old URLs straight at their final destination whenever you can.

Index routes that redirect

A section often has no content of its own, only a default child. Instead of duplicating the child, redirect to it. In real React Router the to can be relative to the route, so the parent path does not have to be repeated:

JSX
// App.jsx - React Router (read-only)
<Route path="settings" element={<SettingsLayout />}>
  <Route index element={<Navigate to="profile" replace />} />
  <Route path="profile" element={<Profile />} />
  <Route path="billing" element={<Billing />} />
</Route>

Visiting /settings renders the layout with the index route inside it, the index route redirects to /settings/profile, and the address bar shows the final URL. Choose this when /settings should not stay a valid, bookmarkable address of its own. If it is fine for /settings to show a summary or a menu, use a normal index page instead, and do not redirect.

push versus replace

Every location change either pushes a new entry onto the browser's history stack or replaces the current one. A redirect should almost always replace. Here is why:

  1. The user clicks a link to /old-blog. The router pushes /old-blog.
  2. <Navigate to="/blog" /> runs. If it pushes, the stack is now /, /old-blog, /blog.
  3. The user presses Back. They land on /old-blog, which immediately redirects forward to /blog again. The back button looks broken: the user is trapped.

With replace, step 2 overwrites the /old-blog entry, so the stack is /, /blog and Back leaves to the previous page as expected.

flowchart LR
    subgraph sgPush["Navigate without replace"]
        P1["/"] --> P2["/old-blog"] --> P3["/blog (current)"]
    end
    subgraph sgReplace["Navigate with replace"]
        R1["/"] --> R3["/blog (current)"]
    end

Without replace the redirecting URL stays in the history, so Back lands on it and bounces the user forward again.

The following demo uses a tiny in-memory history (an array and an index) instead of the real browser history, so you can watch the stack. The router below is a stand-in for how any router handles push, replace and Back.

Why redirects should replace

Do this twice. First leave the box unchecked, click "Open /old-blog" and then "Back": you stay on Blog, because Back lands on /old-blog and the redirect pushes you forward again. Then reload the example, tick the box, repeat, and Back reaches Home. Note the stack: with replace it never contains /old-blog.

Redirects with state and conditions

<Navigate> is also the natural way to redirect from a component that decides while rendering: render nothing, or the redirect, instead of the page.

JSX
// AccountPage.jsx - React Router (read-only)
import { Navigate, useLocation } from 'react-router';

export default function AccountPage({ user }) {
  const location = useLocation();
  if (!user) {
    return <Navigate to="/login" replace state={{ from: location }} />;
  }
  return <h1>Hello, {user.name}</h1>;
}

The state carries the page the user wanted, so the login page can send them back after signing in. Protected Routes and Auth Redirects builds this into a reusable guard.

Two related facts for later chapters. First, in data mode and framework mode you can redirect before a route renders, by returning redirect('/login') from a loader or action (the response carries a redirect status), which avoids a flash of the wrong page. Second, redirects done by <Navigate> happen in the browser, so a search engine that does not run your JavaScript sees the old URL as a normal page. For permanent moves of public URLs, also configure a real HTTP redirect (301 or 308) on your server or CDN.

Redirect loops

A redirect loop happens when redirects point at each other, directly (/a to /b to /a) or through a longer cycle, or when a redirect fires under a condition that the redirect itself never changes. A typical bug: "logged-out users go to /login" plus "the login page requires being logged out", which redirects back. The browser tab spins and the history may fill with entries.

Prevent loops by keeping redirects acyclic: draw them as arrows and check that every chain ends at a page that renders. Use replace, so history does not fill up. Make sure the destination does not match the condition that triggered the redirect, for example never guard the login route itself.

The stand-in below counts redirects in a chain and stops after four, so you can see a loop without freezing the page. (The real router would keep going.)

Spotting a redirect loop

"Start (loops)" bounces between /a and /b until the guard stops it and prints the chain. "Fixed chain" makes one hop and lands on a page that actually renders. In real apps, the chain you print in a bug report is the fastest way to find which two rules disagree.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does <Navigate to='/blog' replace /> do when it is rendered?

    Navigate renders nothing visible; when it mounts it moves to the new location. The replace prop makes it overwrite the current history entry instead of adding one.
  2. 2. A redirect from /old-blog to /blog uses push instead of replace. What goes wrong?

    With push, /old-blog stays in the history stack. Going back lands on it and the redirect fires again. Replace removes that entry.
  3. 3. You want /docs/guides/setup to be the destination for /old-docs/guides/setup. How do you keep the rest of the path?

    The splat value holds the rest of the URL. A small component can read it and render Navigate with a path built from it.
  4. 4. Which situation is most likely to produce a redirect loop?

    The login page matches the very condition that triggers the redirect, so it redirects to itself forever. A redirect target must never satisfy the redirecting rule.

Summary

  • <Navigate to="..." /> renders nothing and moves the user when it mounts; use it for redirects decided during rendering.
  • Use replace for redirects, so the redirecting URL does not stay in history and Back keeps working.
  • Redirect old URLs straight to their final target, keep splats by building the new path from useParams()['*'], and use relative to values for index redirects.
  • Pass state to remember where the user came from, as login flows do; in data mode redirect() from a loader does the same job before rendering.
  • Client redirects do not send HTTP redirect statuses; configure 301/308 on the server for permanent public moves.
  • Redirects must form an acyclic chain, and a redirect target must never match the rule that caused the redirect.

Next: Nested Routes and Outlet