Protected Routes in React
In this lesson, you will learn how to create protected routes in React using React Router. Protected routes restrict access to specific pages based on conditions such as whether a user is logged in.
1. What Are Protected Routes?
A protected route is a route that allows access only when a particular condition is satisfied. For example, an application may allow only logged-in users to access a Dashboard page.
Consider an application with Login, Home, and Dashboard pages. Anyone can open the Home page, but the Dashboard page should be accessible only after login.
Real-Life Example
- Home Page: Available to every visitor.
- Login Page: Allows users to sign in.
- Dashboard Page: Intended for authenticated users.
2. How Protected Routes Work
When a user tries to open a protected page, the application checks whether the user is logged in. If the condition is satisfied, the requested page is displayed. Otherwise, the user is redirected to the Login page.
Yes → Show Dashboard
→ Redirect to Login
This process provides a better user experience by directing users to the appropriate page according to their authentication status.
3. Import Required Components
React Router provides components such as
Routes, Route, Navigate,
and Link for managing application navigation.
The Navigate component can redirect a user to another
route when a condition is not satisfied.
import {
BrowserRouter,
Routes,
Route,
Navigate,
Link
} from "react-router-dom";
import { useState } from "react";
BrowserRouterenables browser-based routing.Routesgroups route definitions.Routemaps a URL to a component.Navigateredirects users to another route.useStatestores the example login state.
4. Create the Login Page
First, create a Login component. For this learning example, a
button changes the login state to true. In a real
application, login status should be established only after the
server successfully authenticates the user's credentials.
function Login({ onLogin }) {
return (
<div>
<h2>Login Page</h2>
<p>Please log in to access your dashboard.</p>
<button onClick={onLogin}>
Login
</button>
</div>
);
}
export default Login;
The onLogin prop receives a function from the parent
component. When the user clicks the Login button, that function
updates the login state.
5. Create the Dashboard Page
The Dashboard component represents a page that should be available only after the user has logged in.
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
<p>Welcome! You have accessed the dashboard.</p>
</div>
);
}
export default Dashboard;
The Dashboard component contains the content that we want to show when the protected route's login condition is satisfied.
6. Create a Protected Route Component
We can create a reusable ProtectedRoute component.
It receives the login status and the page that should be displayed.
If the user is logged in, the component renders its
children. If the user is not logged in, it renders
Navigate to redirect the user to the Login page.
import { Navigate } from "react-router-dom";
function ProtectedRoute({ isLoggedIn, children }) {
if (!isLoggedIn) {
return <Navigate to="/login" replace />;
}
return children;
}
export default ProtectedRoute;
Understanding the Code
-
isLoggedInindicates whether the user is logged in. -
childrenrepresents the component placed inside the protected route. -
if (!isLoggedIn)checks whether the user is not logged in. -
Navigateredirects the user to the Login page. -
replacereplaces the current history entry instead of adding another one. -
return childrendisplays the requested page when the condition is satisfied.
! operator means NOT.
Therefore, !isLoggedIn is true when
isLoggedIn is false.
7. Configure the Protected Route
Now connect the Login, Home, and Dashboard components using React
Router. The Dashboard route is wrapped inside
ProtectedRoute.
import { useState } from "react";
import {
BrowserRouter,
Routes,
Route,
Link
} from "react-router-dom";
import Login from "./Login";
import Dashboard from "./Dashboard";
import ProtectedRoute from "./ProtectedRoute";
function Home() {
return (
<div>
<h2>Home Page</h2>
<p>Welcome to the application.</p>
</div>
);
}
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
const handleLogin = () => {
setIsLoggedIn(true);
};
return (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>{" "}
<Link to="/login">Login</Link>{" "}
<Link to="/dashboard">Dashboard</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/login"
element={
<Login onLogin={handleLogin} />
}
/>
<Route
path="/dashboard"
element={
<ProtectedRoute isLoggedIn={isLoggedIn}>
<Dashboard />
</ProtectedRoute>
}
/>
</Routes>
</BrowserRouter>
);
}
export default App;
How It Works
-
The initial login state is
false, so the user is not logged in. -
The user opens
/dashboard. -
ProtectedRoutechecks the value ofisLoggedIn. -
Because the value is false, the user is redirected to
/login. - Clicking the demonstration Login button changes the state to true.
-
Opening
/dashboardnow displays the Dashboard.
8. Expected Output
Before Login
Login Page
Please log in to access your dashboard.
[ Login ]
If the user opens /dashboard before logging in,
the application redirects to /login.
After Clicking Login
Dashboard
Welcome! You have accessed the dashboard.
The Dashboard can now be displayed because the example login state is true.
9. Common Mistakes
-
Forgetting the wrapper: If the Dashboard route
is not wrapped in
ProtectedRoute, the custom condition will not protect that route. -
Using the wrong path: The redirect destination
must match the configured Login route, such as
/login. - Incorrect login condition: Check that the component redirects only when the user is not logged in.
- Assuming client-side protection is enough: React routing does not replace server-side authorization.
- Using a fake login in production: The sample button is for learning only and does not authenticate users.
10. Practice Tasks
Task 1: Protect a Profile Page
Create a Profile component and allow users to access it only when the login condition is true.
Task 2: Add a Logout Button
Add a Logout button that sets the demonstration login state back to false. After logout, opening the Dashboard should redirect the user to the Login page.
Task 3: Protect Multiple Routes
Protect both the Dashboard and Profile routes by reusing the
same ProtectedRoute component.
Task 4: Display a Login Message
Update the Login page to display a message explaining that login is required before opening the Dashboard.
Summary
In this lesson, you learned how protected routes work in React Router, how to check a user's login state, how to create a reusable ProtectedRoute component, and how to redirect unauthenticated users with Navigate. You also learned how to protect Dashboard pages, understand common mistakes, and practise adding authentication-based navigation. Remember that client-side route protection improves navigation but real security must be enforced by the server or API. Congratulations on completing the React Routing lessons with CIIT Training Institute!