Protected Routes and Role-Based Access Guards
Protected Routes and Role-Based Access Guards
1. Client-Side Security & Access Control
In enterprise portals (learning management systems, corporate intranets, financial dashboards), certain views must be restricted based on user authentication and permissions:
- Guest users should only access
/login,/register, and public catalog pages. - Authenticated students can access
/dashboardand enrolled courses. - Only users with the
adminrole can access/admin/consoleand/admin/billing.
While true security must always be enforced on the backend server (validating JWT tokens on API calls), client-side route guards are essential to provide a seamless user experience, preventing unauthorized users from accessing restricted layouts.
2. Implementing an Authentication Guard (<ProtectedRoute>)
In React Router v6, route guards are implemented as wrapper layout components that render an <Outlet /> if authorized, or <Navigate /> if denied:
3. Configuring Protected Routes in the Route Tree
Using layout wrapping, protecting an entire section of your application requires nesting child routes beneath the guard:
4. Returning Users to Their Intended Destination After Login
Notice line 16: <Navigate to="/login" state={{ from: location }} replace />.
When an unauthorized user attempts to visit /admin/billing, the guard stores the attempted URL in navigation state.
Inside the LoginPage component:
The user is seamlessly redirected right back to the page they were originally trying to access!
Practice Quiz
state={{ from: location }} passed when redirecting an unauthenticated user to /login?<ProtectedRoute>, what does the guard render?Scroll Restoration and Optimistic Route Transitions
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Deferred Data and Suspense Streaming with Await | Scroll Restoration and Optimistic Route Transitions |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.