Protected Routes
Protected Routes cover RequireAuth guards, Outlet nesting, preserving return URLs, permission guards, and why UI guards are not API security.
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
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
<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.
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
replaceand 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
1How do you implement a protected route with nested routes?
BeginnerModel answer
Wrap protected children in a guard route that checks auth and renders<Outlet />when allowed, otherwise<Navigate />to login.2What is the difference between unauthenticated and forbidden?
BeginnerModel answer
Unauthenticated users should sign in.
Forbidden users are signed in but lack permission—show access denied rather than the login form.
Intermediate
3Why is an Outlet useful in a route guard?
IntermediateModel answer
The guard stays as a layout route and renders whichever matched child route is allowed without re-declaring each page inside the guard.
4Why are protected routes not sufficient security?
IntermediateModel answer
They only control UI rendering.
Real security requires backend authentication and authorization on every sensitive API call.
Advanced
5How do you preserve the originally requested URL?
AdvancedModel answer
Passstate={{ 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.