Protecting Routes in React
Route protection in React means restricting access to certain pages based on authentication or authorization.
Example:
-
Logged-in users can access
/dashboard -
Non-authenticated users are redirected to
/login -
Admin-only pages are accessible only to admin users
This is commonly implemented using React Router.
Why Route Protection is Needed
Route protection helps:
-
Prevent unauthorized access
-
Secure sensitive pages
-
Improve user experience
-
Implement role-based access control
Example protected pages:
-
Dashboard
-
Admin panel
-
Profile page
-
Billing section
Basic Idea
When a user navigates to a route:
-
Check whether the user is authenticated
-
If authenticated → allow access
-
Otherwise → redirect to login page
Common Approaches
1. Protected Route Component (Most Common)
This is the standard interview answer.
Example Using React Router v6
import { Navigate } from "react-router-dom";
function ProtectedRoute({ children }) {
const isAuthenticated = localStorage.getItem("token");
if (!isAuthenticated) {
return <Navigate to="/login" replace />;
}
return children;
}
export default ProtectedRoute;
Usage
import { Routes, Route } from "react-router-dom";
<Routes>
<Route path="/login" element={<Login />} />
<Route
path="/dashboard"
element={
<ProtectedRoute>
<Dashboard />
</ProtectedRoute>
}
/>
</Routes>
How It Works
If token exists:
-
User sees Dashboard
If token does not exist:
-
User is redirected to Login page
Role-Based Route Protection
Sometimes routes depend on user roles.
Example:
-
Admin →
/admin -
HR →
/recruitment -
User →
/profile
Example
function AdminRoute({ children }) {
const user = JSON.parse(localStorage.getItem("user"));
if (!user || user.role !== "admin") {
return <Navigate to="/unauthorized" />;
}
return children;
}
Using Context API for Authentication
Instead of checking localStorage everywhere, we usually store auth state in:
-
React Context API
-
Redux
-
Zustand
-
Redux Toolkit
Example:
const { isAuthenticated } = useAuth();
This makes authentication centralized and cleaner.
JWT-Based Authentication
In real-world applications:
-
Backend returns JWT token after login
-
Token stored in:
-
HttpOnly cookies (recommended)
-
localStorage
-
sessionStorage
-
-
Protected routes validate login state using token
Important Security Note
Frontend route protection alone is NOT secure.
Why?
Because frontend code can be manipulated.
Real security must also happen on the backend:
-
APIs must validate tokens
-
Backend must check permissions
-
Unauthorized API requests must be rejected
Interview line:
"React route protection improves UI-level access control, but actual security must always be enforced on the backend."
Lazy Loading + Protected Routes
Often combined together for performance optimization.
Example:
const Dashboard = React.lazy(() => import("./Dashboard"));
Protected routes can wrap lazy-loaded components.
Nested Protected Routes (React Router v6)
Example:
<Route element={<ProtectedRoute />}>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/profile" element={<Profile />} />
</Route>
Using Outlet:
import { Outlet, Navigate } from "react-router-dom";
function ProtectedRoute() {
const isAuthenticated = true;
return isAuthenticated ? <Outlet /> : <Navigate to="/login" />;
}
Interview-Friendly Real-World Flow
Typical authentication flow:
-
User logs in
-
Backend returns token
-
Token stored securely
-
Auth state updated
-
Protected routes check auth state
-
Backend validates token for APIs
Common Interview Questions
Q1: Can protected routes alone secure an application?
No.
Frontend protection only hides UI routes. Backend APIs must also validate authentication and authorization.
Q2: Where should tokens be stored?
Best practice:
-
HttpOnly cookies (most secure)
Other options:
-
localStorage
-
sessionStorage
Q3: Difference between Authentication and Authorization?
| Authentication | Authorization |
|---|---|
| Verifies who user is | Verifies what user can access |
| Login process | Permission control |
Advantages
-
Better user experience
-
Centralized auth handling
-
Prevents unauthorized page access
-
Supports role-based systems
Limitations
-
Frontend-only protection is not fully secure
-
localStorage tokens are vulnerable to XSS attacks
-
Requires backend validation
Short Interview Answer
"Route protection in React is used to restrict access to certain pages based on authentication or user roles. Typically, a ProtectedRoute component checks whether the user is authenticated and either renders the requested component or redirects to the login page using React Router. In real-world applications, backend APIs must also validate tokens because frontend protection alone is not sufficient for security."
