← Back to Chapters

Protected Routes

? Protected Routes

? Quick Overview

Protected routes restrict access to certain pages unless a user is authenticated. They are commonly used for dashboards, profiles, and admin panels.

? Key Concepts

  • Authentication state decides route access
  • Unauthorized users are redirected
  • Reusable route guards improve maintainability

? Syntax / Theory

In React Router v6+, protected routes are implemented using a wrapper component that conditionally renders children or redirects using <Navigate />.

? View Code Example
// 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;

? Example App Setup

? View Code Example
// 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 Logic

? View Code Example
// 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;

?️ Dashboard Component

? View Code Example
// 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-Based Protection

? View Code Example
// 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;
}

? Interactive Demo

User Status: Logged Out
Waiting for action...

? Tips & Best Practices

  • Centralize auth logic using Context or Redux
  • Always use replace to prevent back navigation
  • Wrap multiple routes using a single guard

? Try It Yourself

  1. Create a protected dashboard route
  2. Add role-based access control
  3. Store login state globally

Goal: Master secure routing patterns in React