Skip to main content

Lesson 6 of 10

Protected Routes & Auth Guard

Protected routes prevent unauthorized access to private pages. In React Router v6, the cleanest pattern is a wrapper component that checks auth state and redirects if unauthenticated - while preserving the URL the user was trying to visit.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Protected Route Pattern

Protected Route Pattern
import { Navigate, Outlet, useLocation } from 'react-router-dom';
import { useAuth } from '../hooks/useAuth';

// ProtectedRoute - wraps routes that require authentication
function ProtectedRoute({ allowedRoles }: { allowedRoles?: string[] }) {
  const { user, isLoading } = useAuth();
  const location = useLocation();

  // Still loading (e.g., checking JWT) - don't redirect yet
  if (isLoading) return <PageSpinner />;

  // Not authenticated - redirect to login, preserve intended destination
  if (!user) {
    return <Navigate to="/login" state={{ from: location }} replace />;
    // ↑ state.from lets LoginForm know where to redirect after login
  }

  // Role-based access control (RBAC)
  if (allowedRoles && !allowedRoles.includes(user.role)) {
    return <Navigate to="/403" replace />;
  }

  return <Outlet />; // ← render the protected child routes
}

// Route configuration
function App() {
  return (
    <Routes>
      {/* Public routes */}
      <Route path="/login" element={<LoginPage />} />
      <Route path="/signup" element={<SignupPage />} />
      <Route path="/about" element={<AboutPage />} />

      {/* Protected routes - any authenticated user */}
      <Route element={<ProtectedRoute />}>
        <Route path="/dashboard" element={<DashboardLayout />}>
          <Route index element={<Overview />} />
          <Route path="profile" element={<Profile />} />
        </Route>
      </Route>

      {/* Admin-only routes */}
      <Route element={<ProtectedRoute allowedRoles={['admin']} />}>
        <Route path="/admin" element={<AdminLayout />}>
          <Route index element={<AdminDashboard />} />
          <Route path="users" element={<UserManagement />} />
        </Route>
      </Route>
    </Routes>
  );
}

// useAuth hook - checks auth state
function useAuth() {
  const { data: user, isLoading } = useQuery({
    queryKey: ['currentUser'],
    queryFn: fetchCurrentUser,
    retry: false, // don't retry on 401
    staleTime: 5 * 60 * 1000, // 5 minutes
  });
  return { user, isLoading };
}

Tip

Tip

Practice Protected Routes Auth Guard in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and flow for Protected Routes & Auth Guard

Practice Task

Note

Practice Task - (1) Write a working example of Protected Routes Auth Guard from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Protected Routes Auth Guard is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/10 done