Introduction 😊
So far, you’ve learned how to:
- Set up routing with React Router
- Use
BrowserRouter,Routes, andRoute - Handle dynamic routes using
useParams - Navigate programmatically using
useNavigate
Now let’s talk about a very important real-world concept 🔐
In most applications:
- Some pages should be public (Login, Signup)
- Some pages should be private (Dashboard, Profile, Admin pages)
To control access, we use Protected Routes.
In this lesson, you will learn:
- What protected routes are
- Why they are needed
- How to implement protected routes
- Step-by-step example
- Common beginner mistakes
Let’s begin 🚀
What Are Protected Routes? 🤔
Protected routes are routes that can be accessed only if a condition is true.
Usually the condition is:
- User is logged in ✅
- User has a valid token ✅
- User has a specific role (Admin/User) ✅
👉 If the condition fails, the user is redirected to another page (like Login).
Why Protected Routes Are Important 🧠
Without protected routes:
- Anyone can access private URLs ❌
- Sensitive data can be exposed ❌
- Application security is weak ❌
Protected routes help:
- Secure dashboards 🔐
- Control user access
- Build professional applications
Simple Authentication Example 🔑
For learning purposes, let’s assume:
const isAuthenticated = true;
👉 In real apps, this value comes from:
- Context
- LocalStorage
- Redux
- Auth API
Step 1️⃣: Create a ProtectedRoute Component 🧩
import { Navigate } from "react-router-dom";
function ProtectedRoute({ children }) {
const isAuthenticated = true; // replace with real auth logic
if (!isAuthenticated) {
return <Navigate to="/login" />;
}
return children;
}
export default ProtectedRoute;
📌 This component:
- Checks authentication
- Redirects if not logged in
- Allows access if logged in
Step 2️⃣: Wrap Protected Pages 🔒
import ProtectedRoute from "./ProtectedRoute";
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
</Routes>
👉 Now:
/login→ public/dashboard→ protected
Redirecting Unauthorized Users 🚫
When a user tries to access:
/dashboard
Without authentication:
- They are redirected to:
/login
👉 This improves both security and UX.
Using LocalStorage for Authentication 📦
Example logic:
const isAuthenticated = !!localStorage.getItem("token");
✔ Common approach
✔ Easy to implement
Protected Routes with Context API 🧠
In real apps, authentication state is often stored in Context.
Example:
const { isAuthenticated } = useAuth();
👉 Then use it inside ProtectedRoute.
Role-Based Protected Routes 🧑💼
You can also protect routes based on roles.
Example:
if (role !== "admin") {
return <Navigate to="/unauthorized" />;
}
👉 Useful for:
- Admin panels
- Manager dashboards
Common Beginner Mistakes ❌
- Forgetting to wrap protected routes
- Using
useNavigateinstead ofNavigate - Not checking auth properly
- Hardcoding auth logic permanently
💡 Always centralize authentication logic.
ProtectedRoute vs Conditional Rendering ⚖️
| ProtectedRoute | Conditional Rendering |
|---|---|
| Route-level protection | UI-level control |
| Prevents page access | Only hides UI |
| Recommended | Limited use |
Important Notes 📌
Navigatereplaces oldRedirect(React Router v6)- ProtectedRoute is just a normal component
- Can protect multiple routes easily
Conclusion 🎯
Protected routes are essential for real-world React applications.
Key takeaways:
- Protected routes control access
- They improve security
- Easy to implement with React Router
- Required for dashboards and private pages
👉 If you want production-ready React apps, protected routes are mandatory 🔐💙
Frequently Asked Questions (FAQs) ❓
Can protected routes be bypassed?
Not if authentication is handled correctly.
Should I store tokens in localStorage?
For learning yes, for production consider secure storage.
Can I protect multiple routes at once?
Yes, by wrapping them in the same ProtectedRoute logic.
What’s Next? 🚀
👉 In the next lesson, we will learn:
Lesson 24 — Props Drilling Problem & Context API (Real Example)
Understanding why Context is needed in large applications.