Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 50 ยท Navigating Programmatically

Protected Routes and Auth Redirects

Build protected routes in React Router: an auth context, a guard layout route, redirect to login with a from location, role checks, and why client guards are not security.

Most apps have pages that only signed-in users should see: an account page, a dashboard, an admin panel. A protected route is a route that checks who the visitor is before it shows its content. If the visitor is not signed in, the app sends them to the login page, and after they sign in it brings them back to the page they originally wanted.

React Router has no built-in "protected" flag. Instead you build the guard from pieces you already know: a layout route that renders an <Outlet>, the <Navigate> component or useNavigate, and the location state you can attach to a navigation. This lesson shows the whole pattern, runs a working stand-in, and then explains the most important caveat: a guard in the browser improves the experience, but it does not protect your data.

The pattern in four parts

  1. An auth context that holds the current user (or null) plus login and logout functions. Any component can read it with a hook. If you are new to context, read Context; Authentication Patterns covers how sessions and tokens work.
  2. A guard layout route. It has no path of its own. It renders <Outlet /> when the user is signed in and redirects to /login otherwise. Every route nested inside it is protected, with no repeated checks.
  3. A from value. When the guard redirects, it passes the location the visitor wanted in the navigation state. The login page reads it and returns there after a successful sign-in.
  4. A role check (optional): a second guard that compares user.role with the role a section requires.
flowchart TD
  V["Visitor opens /account"] --> G{"Signed in?"}
  G -- "yes" --> R{"Role allowed?"}
  G -- "no" --> L["Redirect to /login<br/>state: from = /account"]
  R -- "yes" --> P["Render the page via Outlet"]
  R -- "no" --> F["Show a 403 message"]
  L --> S["Login succeeds"]
  S --> B["navigate to the saved from location"]

The guard sends signed-out visitors to the login page and remembers where they were going.

The real React Router code

Here is the pattern in declarative mode. This is the real library API and it is read-only, because the live editor cannot install react-router.

JSX
// AuthContext.jsx (real React Router app, read-only)
import { createContext, useContext, useState } from 'react';

const AuthContext = createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null);
  const value = {
    user,
    login: (nextUser) => setUser(nextUser),
    logout: () => setUser(null),
  };
  return <AuthContext value={value}>{children}</AuthContext>;
}

export const useAuth = () => useContext(AuthContext);
JSX
// RequireAuth.jsx (real React Router, read-only)
import { Navigate, Outlet, useLocation } from 'react-router';
import { useAuth } from './AuthContext';

export function RequireAuth() {
  const { user } = useAuth();
  const location = useLocation();

  if (!user) {
    return <Navigate to="/login" replace state={{ from: location.pathname }} />;
  }
  return <Outlet />;
}
JSX
// App.jsx (real React Router, read-only)
import { BrowserRouter, Routes, Route } from 'react-router';

export default function App() {
  return (
    <AuthProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/login" element={<Login />} />

          <Route element={<RequireAuth />}>
            <Route path="/account" element={<Account />} />
            <Route element={<RequireRole role="admin" />}>
              <Route path="/admin" element={<Admin />} />
            </Route>
          </Route>
        </Routes>
      </BrowserRouter>
    </AuthProvider>
  );
}
JSX
// Login.jsx (real React Router, read-only)
import { useLocation, useNavigate } from 'react-router';

export function Login() {
  const { login } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const from = location.state?.from ?? '/account';

  async function handleSubmit(event) {
    event.preventDefault();
    const user = await signIn(new FormData(event.currentTarget));
    login(user);
    navigate(from, { replace: true });
  }

  return <form onSubmit={handleSubmit}>{/* fields */}</form>;
}

Three details deserve a closer look.

replace on the redirect. <Navigate replace> swaps the protected URL for /login in the history stack. Without it, the back button from the login page returns to /account, which immediately redirects to /login again, and the user is stuck in a loop they can only escape with a double click.

replace after login. For the same reason, navigate(from, { replace: true }) removes the login page from history. Pressing back after signing in should not show a login form to a signed-in user.

The route without a path. <Route element={<RequireAuth />}> only adds a wrapper. It does not change any URL, so /account stays /account. This is the same trick as a layout route.

Try it: a guard with a login redirect

The stand-in below has the same structure. It is built from React and window.location.hash, with a tiny router that supports nested route objects and an Outlet. Navigation state is kept in a variable instead of the browser history, because the sandbox blocks the History API. Everything else (the context, the guard, the from handling, the role check) is the same code you would write with the real library.

Try this order: open Account while signed out and watch the redirect, sign in as Ada, and notice that you land on Account, not on a default page. Then sign out, try Admin as Ada (the 403 appears), and finally sign in as Root.

A guard layout route with redirect and roles

What is real here and what is a stand-in? The context, RequireAuth, RequireRole, Login and the pages are exactly what you would write with React Router. Routes, Outlet, Navigate, useLocation and navigate are the stand-in: they imitate the real components for this lesson but do no ranking, no relative paths and no real history entries.

Role-based routes

The RequireRole guard above shows the second layer. Authentication answers "who are you?", while authorization answers "what may you do?". Keep the two checks separate:

  • A signed-out visitor is redirected to login, because signing in might fix the problem.
  • A signed-in visitor with the wrong role gets a 403 message (or a redirect to a "not allowed" page), because signing in again will not help.

If you have many roles, resist writing a guard per role. Pass the requirement in as a prop (<RequireRole role="admin" />), or store it in the route's handle and read it in one guard.

Do not render a flash of the wrong screen while the app is still working out who the user is. If you restore a session from a cookie on page load, the first render has no user yet, and a naive guard would redirect a signed-in person to /login. Give your auth context a third state ('loading') and render a spinner until it is known.

Why client-side guards are not security

Everything in a React app is delivered to the visitor's browser: the JavaScript for the admin page, the route table, and the guard code. The visitor controls that browser. They can open the developer tools, edit a variable, call your API with curl, or read the bundle. A guard that hides the admin page is a user interface decision, like graying out a button. It stops honest users from landing on a page that would fail, and nothing more.

Real protection lives on the server. Every API request that returns private data or changes something must check the session and the permission itself, and answer 401 (not signed in) or 403 (not allowed). The next example makes the difference concrete: a pretend server decides what data is returned, and you can bypass the guard to prove that the shell is visible but the data stays out of reach.

The guard hides the page, only the server protects the data

With the guard intact, only the admin token shows the page. Tick the checkbox and the page appears for everyone, as if a visitor had deleted the guard in the dev tools. But for the signed-out and member tokens the server still answers 401 or 403, and no secret data appears. That is the correct design: the guard is for comfort, the server is for safety.

Where to go from here

With data routers you can also run the check in a loader that throws a redirect('/login'). That is better than a component guard because it happens before the page renders, so there is no flash of protected UI and no wasted work. You will build that version in Authentication with Loaders and Actions, and a full dashboard in the dashboard project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a guard layout route in React Router?

    A guard layout route has no path. Its element either renders <Outlet /> for the nested routes or redirects, so one check protects every child route.
  2. 2. Why pass state={{ from: location.pathname }} when redirecting to the login page?

    The login page reads location.state.from after a successful sign-in and navigates back there. Without it, everyone would land on a default page.
  3. 3. Why use the replace option on the redirect to login?

    Without replace, going back from /login returns to /account, which redirects to /login again. Replacing the entry keeps the history clean.
  4. 4. A teammate says the admin page is secure because the guard redirects non-admins. What is wrong with that claim?

    Client code can be edited or skipped. Private data must be protected by server-side checks that answer 401 or 403.

Summary

  • A protected route is built from an auth context, a pathless guard layout route with <Outlet />, and <Navigate> or a redirect.
  • Pass the wanted location as state.from so the login page can send the visitor back, and use replace to keep history clean.
  • Separate authentication (redirect to login) from authorization (403 for a wrong role).
  • Handle a 'loading' auth state so a signed-in user is not flashed to the login page.
  • Client guards are a user-experience feature. Only server-side checks protect data.

Next: Blocking Navigation