MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Protected Routes and Role-Based Access Guards0%
Study Materials
React.js for AdvancedProgress 0%
1.1Control Props and Inversion of Control Pattern1.2State Reducer Pattern in Advanced React1.3Prop Getters and Flexible Design Systems1.4Headless UI Architecture and Accessibility Primitives
4.1React Router v6 Data Loaders and Actions4.2Deferred Data and Suspense Streaming with Await4.3Protected Routes and Role-Based Access Guards4.4Scroll Restoration and Optimistic Route Transitions
HomeTutorialsReact.js for AdvancedProtected Routes and Role-Based Access Guards
Scroll Restoration and Optimistic Route Transitions

Protected Routes and Role-Based Access Guards

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

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 /dashboard and enrolled courses.
  • Only users with the admin role can access /admin/console and /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.

1Route Request: /admin/analytics
2 │
3 ▼
4[Protected Route Guard]
5 ├─ Not Authenticated? ──► Redirect to /login with state: { from: location }
6 ├─ Wrong Role (Student)? ──► Redirect to /unauthorized (HTTP 403 screen)
7 └─ Authorized (Admin)? ──► Render <Outlet /> (Access Granted!)

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:

1// src/components/ProtectedRoute.jsx
2import React from 'react';
3import { Navigate, Outlet, useLocation } from 'react-router-dom';
4import { useAuth } from '../context/AuthContext';
5 
6export default function ProtectedRoute({ allowedRoles }) {
7 const { user, isAuthenticated, loading } = useAuth();
8 const location = useLocation();
9 
10 // 1. Show spinner while verifying stored session
11 if (loading) {
12 return <div className="loading-screen">Authenticating session...</div>;
13 }
14 
15 // 2. Unauthenticated: Redirect to login, preserving intended destination!
16 if (!isAuthenticated) {
17 return <Navigate to="/login" state={{ from: location }} replace />;
18 }
19 
20 // 3. Role-Based Access Control (RBAC) check
21 if (allowedRoles && !allowedRoles.includes(user.role)) {
22 return <Navigate to="/unauthorized" replace />;
23 }
24 
25 // 4. Authorized: Render matching child route!
26 return <Outlet />;
27}

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:

1// src/App.jsx
2import { Routes, Route } from 'react-router-dom';
3import ProtectedRoute from './components/ProtectedRoute';
4import PublicLayout from './layouts/PublicLayout';
5import StudentDashboard from './pages/StudentDashboard';
6import AdminConsole from './pages/AdminConsole';
7import LoginPage from './pages/LoginPage';
8import UnauthorizedPage from './pages/UnauthorizedPage';
9 
10export default function App() {
11 return (
12 <Routes>
13 {/* Public Routes */}
14 <Route path="/" element={<PublicLayout />} />
15 <Route path="/login" element={<LoginPage />} />
16 <Route path="/unauthorized" element={<UnauthorizedPage />} />
17 
18 {/* Authenticated Routes (Students & Admins) */}
19 <Route element={<ProtectedRoute />}>
20 <Route path="/dashboard" element={<StudentDashboard />} />
21 <Route path="/profile" element={<StudentProfile />} />
22 </Route>
23 
24 {/* Restricted Admin Routes (Admins Only!) */}
25 <Route element={<ProtectedRoute allowedRoles={['admin', 'superadmin']} />}>
26 <Route path="/admin" element={<AdminConsole />} />
27 <Route path="/admin/billing" element={<AdminBilling />} />
28 </Route>
29 </Routes>
30 );
31}

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:

1const location = useLocation();
2const navigate = useNavigate();
3 
4// After successful login:
5const destination = location.state?.from?.pathname || '/dashboard';
6navigate(destination, { replace: true });

The user is seamlessly redirected right back to the page they were originally trying to access!


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What is the primary role of a client-side Protected Route in React Router?
Question 2
What component does React Router v6 use to redirect users declaratively?
Question 3
Why is state={{ from: location }} passed when redirecting an unauthenticated user to /login?
Question 4
If an authorized user passes the permission check in <ProtectedRoute>, what does the guard render?
Question 5
Can client-side route guards replace backend API authorization?
Next Lesson

Scroll Restoration and Optimistic Route Transitions

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
Deferred Data and Suspense Streaming with AwaitScroll Restoration and Optimistic Route Transitions

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Advanced with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext