Protected Routes — Complete Guide
Protected Routes — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of React.js Tutorial on Toolliyo Academy.
On this page
React.js Tutorial · Lesson 33 of 100
Protected Routes
Beginner ✓ → Intermediate → Advanced → Professional
Intermediate · 2 — Build apps · ~14 min read · Module 4: Routing & Data
Introduction
You know the basics now. Here we use Protected Routes in real app situations — forms, pages, and data. Still plain language, just a bit more depth. A protected route blocks access when the user is not logged in. Usually you check auth state and redirect to /login with Navigate. Account pages, admin tools, and checkout must not be visible to strangers.
Routing is how a single React app feels like many pages. Users expect URLs like /cart and /checkout — Router makes that work.
When will you use this?
Add routing when your app has more than one screen and URLs should be bookmarkable.
- Multi-page apps like dashboards use React Router — /settings, /profile, /orders.
- E-commerce sites route /product/123 to a product detail component.
Real-world: Toolliyo instructor admin gate
Only users with role instructor or admin may open /admin/analytics. ProtectedRoute checks JWT role claim and redirects students to /courses.
Production-style code
function ProtectedRoute({ roles, children }) {
const { user, loading } = useAuth();
if (loading) return <Spinner />;
if (!user) return <Navigate to="/login" replace state={{ from: location.pathname }} />;
if (roles && !roles.includes(user.role)) return <Navigate to="/forbidden" replace />;
return children;
}
<Route
path="/admin/*"
element={
<ProtectedRoute roles={['admin', 'instructor']}>
<AdminLayout />
</ProtectedRoute>
}
/>
What happens in production: Grade books and payout reports stay behind auth — same guard wraps dozens of nested admin routes.
Lesson example (start here)
Copy this smaller example first. Once it works, compare it with the real-world code above.
import { Navigate } from 'react-router-dom';
function ProtectedRoute({ children }) {
const { user, loading } = useAuth();
if (loading) return <p>Loading...</p>;
if (!user) return <Navigate to="/login" replace />;
return children;
}
<Route path="/account" element={
<ProtectedRoute><Account /></ProtectedRoute>
} />
Line-by-line walkthrough
| Code | What it means |
|---|---|
import { Navigate } from 'react-router-dom'; | Imports code from React or another file so you can use it here. |
function ProtectedRoute({ children }) { | React Router — maps URLs to page components. |
const { user, loading } = useAuth(); | Part of the Protected Routes example — read it together with the lines before and after. |
if (loading) return <p>Loading...</p>; | Sends UI or a value back to whoever called this function. |
if (!user) return <Navigate to="/login" replace />; | React Router — maps URLs to page components. |
return children; | Sends UI or a value back to whoever called this function. |
} | Closes a block started by { or ( above. |
<Route path="/account" element={ | React Router — maps URLs to page components. |
<ProtectedRoute><Account /></ProtectedRoute> | React Router — maps URLs to page components. |
} /> | Closes a block started by { or ( above. |
How it works (big picture)
- useAuth is your hook or context that holds the logged-in user.
- Navigate replace avoids stacking history entries.
Do this on your computer
- Store user in Context or state after login.
- Build ProtectedRoute wrapper.
- Wrap private Route elements with it.
- Read the real-world section and name which part of the app uses this topic.
- Run the example locally and confirm the same behavior in the browser.
- Change one value in the example (text, initial state, or URL) and predict what will happen before you save.
Experiments — try changing this
- Change text or labels in the example and save — watch the browser update.
- Break the code on purpose (remove a bracket), read the error message, then fix it.
- Open React DevTools (browser extension) while running Protected Routes and inspect component props/state.
Remember
Check auth before rendering private pages. Redirect with Navigate when not logged in. Always protect APIs on the server too.
Common questions
Where to store JWT?
Prefer httpOnly cookies set by the server; avoid localStorage for sensitive tokens if you can.
How long should I spend on Protected Routes?
Until you can explain it in your own words and run the example without looking at the answer. Beginners often need 30–60 minutes per new hook or routing topic; setup lessons may take one afternoon.
What if I get stuck on Protected Routes?
Re-read the line-by-line walkthrough, check the browser console for red errors, and compare your code character-by-character with the example. Search the exact error text — someone else had it too.
Where is Protected Routes used in real jobs?
See the real-world section above — the same pattern appears in LMS, banking, e-commerce, and SaaS products. Interviewers ask you to explain it using one concrete example from your project or this lesson.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!