Stop 12 · Authentication & SecurityTopics · 6/12

Protected Routes in React

Part of the MERN Stack Roadmap

In short

Some pages, like My Orders or the admin dashboard, should only open for logged-in users. A protected route checks the login state and politely sends everyone else to the login page, then brings them back after login.

A protected route component checks whether the user is logged in and either renders the page or redirects to /login, remembering where the user wanted to go.

The jaadu in an usher's vest stands at a cinema hall door holding a torch, checking a ticket before letting a movie-goer through the curtain.

Think of it like this

The cinema ticket checker

At a PVR screen entrance, the usher checks your ticket. No ticket, and you are sent to the counter. Once you buy one, the usher remembers which screen you were heading to and lets you in. A protected route is that usher. The real security is still the server, like the projector only playing for paid shows.

Watch it happen

Visiting /orders while logged out

/orders
Check session
/login
Logged in
Back to /orders

1/5Meera opens /orders from a bookmark.

The big ideas

What you need to know

UI guard, not security

Anyone can change JavaScript in their browser. The Express API must still check the token on every protected route.

Wait for loading

On refresh the user is unknown for a moment. Show a loader until /api/auth/me answers, or logged-in users get bounced to login.

Remember where they were going

Pass state={{ from: location }} to Navigate, and redirect there after login.

Role checks too

An AdminRoute can check user.role === "admin" and show a Not allowed page for others.

See it in code

Walk through the code

jsx
1// src/routes/ProtectedRoute.jsx2import { Navigate, Outlet, useLocation } from "react-router-dom";3import { useAuth } from "../context/AuthContext";4 5export default function ProtectedRoute({ roles }) {6  const { user, loading } = useAuth();7  const location = useLocation();8 9  if (loading) return <p>Checking your session...</p>;10  if (!user) return <Navigate to="/login" replace state={{ from: location }} />;11  if (roles && !roles.includes(user.role)) return <Navigate to="/" replace />;12 13  return <Outlet />;14}15 16// src/App.jsx17<Routes>18  <Route path="/login" element={<Login />} />19  <Route element={<ProtectedRoute />}>20    <Route path="/orders" element={<Orders />} />21    <Route path="/profile" element={<Profile />} />22  </Route>23  <Route element={<ProtectedRoute roles={["admin"]} />}>24    <Route path="/admin" element={<AdminDashboard />} />25  </Route>26</Routes>27 28// In Login after a successful login:29// const from = location.state?.from?.pathname || "/";30// navigate(from, { replace: true });

1/6Read the user from your auth context and the current location from React Router.

A layout route that guards a whole group of pages, with optional roles.

Save yourself the pain

Common mistakes

Oops

Relying only on the React guard to protect admin data.

Do this instead

The API must check the token and role too. The guard only improves the user experience.

Oops

Redirecting to /login while the auth check is still loading.

Do this instead

Track a loading flag in your auth context and render a loader until it finishes.

Oops

Using navigate("/login") inside render.

Do this instead

Return <Navigate /> during render. Call navigate() only in event handlers or effects.

Your mission

Guard your notes app

~40 min

Quick check

A user refreshes /orders while logged in and briefly lands on /login. What is the most likely cause?

Go deeper

  1. 1Build a ProtectedRoute wrapper with React Router's Navigate component.
  2. 2Load the current user from /api/auth/me when the app starts.
  3. 3Show a loading state while auth is being checked so pages do not flash.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge