React Tutorial 0/120 lessons ~6 min read Lesson 58

    Protected Routes

    Protected Routes cover RequireAuth guards, Outlet nesting, preserving return URLs, permission guards, and why UI guards are not API security.

    Course progress0%
    Focus
    11 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Course: React — Routing & API Integration Lesson: 13

    Learning objectives

    Create route guards for authenticated users, preserve intended destinations, handle permission-based UI, and understand why route protection is not a backend security boundary.

    What is a protected route?

    A protected route is a route whose UI should be available only when the application has established an appropriate authentication state. Examples include /dashboard, /billing, and /admin/users.

    The route guard improves navigation and user experience. It does not replace API authorization.

    Require authentication

    javascript
    import { Navigate, Outlet, useLocation } from "react-router-dom";
    import { useAuth } from "./AuthProvider";
    function RequireAuth() {
    const { status } = useAuth();
    const location = useLocation();
    if (status === "checking") {
    return <FullPageLoader />;
    }
    if (status !== "authenticated") {
    return <Navigate to="/login" replace state={{ from: location }} />;
    }
    return <Outlet />;
    }

    The guard waits while session restoration is in progress, redirects unauthenticated users, and preserves the requested location so the application can return them after login.

    Configure protected route groups

    javascript
    <Routes>
    <Route path="/login" element={<LoginPage />} />
    <Route element={<RequireAuth />}>
    <Route path="/dashboard" element={<DashboardPage />} />
    <Route path="/orders" element={<OrdersPage />} />
    <Route path="/settings" element={<SettingsPage />} />
    </Route>
    </Routes>

    The guard renders an Outlet when access is allowed.

    Return to the intended page

    After successful login, read the saved location from router state and navigate there, with a safe fallback such as /dashboard. Validate redirect destinations if the application supports externally supplied return URLs; do not blindly redirect to arbitrary external locations.

    Role and permission checks

    A user may be authenticated but lack a specific permission. A separate permission guard can check a capability such as manage_users and render an access-denied page when it is absent. Prefer capability-based checks over spreading role-name comparisons throughout the UI.

    javascript
    function RequirePermission({ permission }) {
    const { can } = usePermissions();
    return can(permission) ? <Outlet /> : <AccessDeniedPage />;
    }

    The backend must independently enforce the same business authorization rules.

    Common edge cases

    • Session status is still checking.
    • Session expires while a protected page is open.
    • User signs in but the original destination no longer exists.
    • User is authenticated but lacks permission.
    • User signs out while protected data remains cached.

    Common mistakes

    • Redirecting before session restoration completes.
    • Forgetting replace and creating confusing history entries.
    • Protecting only the navigation menu but not the route.
    • Assuming route guards secure APIs.
    • Returning to an unsafe external redirect URL.
    • Leaving user-specific cached data visible after logout.

    Best practices

    Centralize guard logic, preserve intended destinations safely, distinguish unauthenticated from forbidden states, clear sensitive cached state on logout, and enforce every permission on the backend.

    Interview questions & answers

    Interview preparation

    5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.

    Beginner

    2
    1. 1How do you implement a protected route with nested routes?
      Beginner

      Model answer

      Wrap protected children in a guard route that checks auth and renders <Outlet /> when allowed, otherwise <Navigate /> to login.
    2. 2What is the difference between unauthenticated and forbidden?
      Beginner

      Model answer

      Unauthenticated users should sign in.

      Forbidden users are signed in but lack permission—show access denied rather than the login form.

    Intermediate

    2
    1. 3Why is an Outlet useful in a route guard?
      Intermediate

      Model answer

      The guard stays as a layout route and renders whichever matched child route is allowed without re-declaring each page inside the guard.

    2. 4Why are protected routes not sufficient security?
      Intermediate

      Model answer

      They only control UI rendering.

      Real security requires backend authentication and authorization on every sensitive API call.

    Advanced

    1
    1. 5How do you preserve the originally requested URL?
      Advanced

      Model answer

      Pass state={{ from: location }} on redirect to login, then navigate back after success with a safe fallback.

    Practice

    Protect Dashboard and Orders for authenticated users. Restrict Administration to users with manage_users. Test session-checking, expired session, insufficient permission, and successful login return navigation.

    Ready to mark this lesson complete?Track your journey across the entire course.