Role-Based Routing System in React

Role-Based Routing System in React

📌 Problem Statement

In many applications, different user roles (e.g., Admin, Manager, User) must have access to different sets of routes and components.

🎯 Objective:

  • Restrict routes based on user role (e.g., /admin only for Admins).

  • Prevent unauthorized access both at UI and route level.

  • Provide fallback UI (e.g., “Access Denied” or “Not Found”).


✅ Requirements

  1. User roles (e.g., admin, editor, viewer) determine route access.

  2. Routes should not render unauthorized components.

  3. Navigation menus must adapt to allowed routes.

  4. Route protection should be centralized and scalable.


🧠 Design Approach

We will:

  • Store user role in auth context (from login).

  • Define route config with allowed roles.

  • Use a PrivateRoute wrapper to check access.

  • Redirect or show "Unauthorized" when blocked.


🗺️ Flow Diagram

LLD Flow Diagram

📁 File Structure


⚙️ 1. Auth Provider – auth/AuthProvider.jsx


🛣️ 2. Route Config – routes/RouteConfig.js


🛡️ 3. PrivateRoute – routes/PrivateRoute.jsx


🗺️ 4. App Router – App.jsx


📄 5. Pages

pages/AdminPage.jsx

pages/DashboardPage.jsx

pages/LoginPage.jsx

pages/Unauthorized.jsx


🔗 6. Navbar (Optional) – components/Navbar.jsx


💡 Tips for Scaling

  • Store role in JWT and decode on login.

  • Extend route config to include metadata like title, icon, menuVisible.

  • Add role-specific layouts (e.g. admin panel shell).

  • Fetch role-based routes from the server if needed.


✅ Summary

With this Role-Based Routing LLD, you’ve implemented:

  • 🔐 Protected routes with access control.

  • 🧠 Context-driven authentication.

  • 🛡️ Dynamic route configuration.

  • 🔁 Reusable guard logic.


🔥Final Conclusion

In this Low-Level Design (LLD) article, we explored how to implement a Role-Based Routing System in React that is secure, scalable, and maintainable.

By leveraging React Context API, a centralized route configuration, and a reusable PrivateRoute guard, we created a system that:

  • 🔐 Restricts access to routes based on user roles.

  • 🧠 Keeps user state centralized and shareable across components.

  • 🔁 Allows easy scalability as new roles and pages are added.

  • 🛡️ Provides a user-friendly fallback (/unauthorized) for blocked access.

We also supported this with a clear flow diagram, modular file structure, and a complete React implementation with reusable logic.

This pattern is essential in real-world applications such as:

  • Admin dashboards

  • Multi-tenant systems

  • SaaS platforms with tiered access

To view or add a comment, sign in

Others also viewed

Explore topics