Protected routes restrict access to certain pages unless a user is authenticated. They are commonly used for dashboards, profiles, and admin panels.
In React Router v6+, protected routes are implemented using a wrapper component that conditionally renders children or redirects using <Navigate />.
// Protected route wrapper component
import React from "react";
import { Navigate } from "react-router-dom";
function ProtectedRoute({ children, isLoggedIn }) {
if (!isLoggedIn) {
return <Navigate to="/login" replace />;
}
return children;
}
export default ProtectedRoute;
// Main app routes with protected dashboard
import React, { useState } from "react";
import { Routes, Route, Link } from "react-router-dom";
import Home from "./Home";
import Login from "./Login";
import Dashboard from "./Dashboard";
import ProtectedRoute from "./ProtectedRoute";
function App() {
const [isLoggedIn, setIsLoggedIn] = useState(false);
return (
<div>
<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 setIsLoggedIn={setIsLoggedIn} />} />
<Route
path="/dashboard"
element={
<ProtectedRoute isLoggedIn={isLoggedIn}>
<Dashboard />
</ProtectedRoute>
}
/>
</Routes>
</div>
);
}
export default App;
// Login page updates auth state and redirects
import React from "react";
import { useNavigate } from "react-router-dom";
function Login({ setIsLoggedIn }) {
const navigate = useNavigate();
const handleLogin = () => {
setIsLoggedIn(true);
navigate("/dashboard");
};
return (
<button onClick={handleLogin}>
Login
</button>
);
}
export default Login;
// Protected dashboard view
import React from "react";
function Dashboard() {
return (
<div>
<h3>Welcome to Dashboard</h3>
<p>You are authenticated</p>
</div>
);
}
export default Dashboard;
// Role-aware protected route
function ProtectedRoute({ children, isLoggedIn, role, requiredRole }) {
if (!isLoggedIn) return <Navigate to="/login" replace />;
if (requiredRole && role !== requiredRole) {
return <Navigate to="/unauthorized" replace />;
}
return children;
}
replace to prevent back navigationGoal: Master secure routing patterns in React