ReactMedium

Role-based routing

Role-based routing shows or blocks routes depending on the user's role or permissions. Define the allowed roles per route, check them in a guard component or router middleware before rendering (redirect unauthenticated users to login and show a 403 page for authenticated users without access), hide navigation links they cannot use, and always enforce the same permissions on the server.

Design

  1. Model permissions, not just roles: map roles to permissions (admin → users:manage, reports:view) and check permissions in routes and UI. Roles can change without code changes everywhere.
  2. Route metadata: attach required permissions to route definitions (in the route config, a handle property, or a wrapper component).
  3. Guard:
    • No user: redirect to login with next.
    • User lacks permission: render a "403: you don't have access" page (better than silently redirecting).
  4. Navigation: filter menu items with the same can() function.
  5. Server enforcement: every API checks the permission; client checks only shape the UI.

In React Router (data mode)

Use middleware or loaders that throw redirect("/login") or a data("Forbidden", { status: 403 }) response, which the route's ErrorBoundary renders. This avoids rendering the protected component at all.

Edge cases

  • Roles loaded asynchronously: show a loading state, not a 403 flash.
  • Role changes during a session: refetch the user, or handle 403 responses from the API by refreshing permissions.
  • Multi-tenant apps: roles per organization (user.roles[orgId]).

Code example

tsx
1import { Navigate, Outlet, createBrowserRouter, NavLink } from "react-router";
2import { useAuth } from "./auth";
3
4type Permission = "reports:view" | "users:manage" | "billing:manage";
5const ROLE_PERMISSIONS: Record<string, Permission[]> = {
6 viewer: ["reports:view"],
7 admin: ["reports:view", "users:manage", "billing:manage"],
8};
9export const can = (role: string | undefined, p: Permission) => !!role && ROLE_PERMISSIONS[role]?.includes(p);
10
11function RequirePermission({ permission }: { permission: Permission }) {
12 const { user, status } = useAuth();
13 if (status === "loading") return <p>Loading…</p>;
14 if (!user) return <Navigate to="/login" replace />;
15 if (!can(user.role, permission)) return <p role="alert">403: you don't have access to this page.</p>;
16 return <Outlet />;
17}
18
19export function Nav() {
20 const { user } = useAuth();
21 return (
22 <nav>
23 {can(user?.role, "reports:view") && <NavLink to="/reports">Reports</NavLink>}
24 {can(user?.role, "users:manage") && <NavLink to="/admin/users">Users</NavLink>}
25 </nav>
26 );
27}
28
29export const router = createBrowserRouter([
30 { element: <RequirePermission permission="reports:view" />, children: [{ path: "/reports", element: <h1>Reports</h1> }] },
31 { element: <RequirePermission permission="users:manage" />, children: [{ path: "/admin/users", element: <h1>Manage users</h1> }] },
32 { path: "/login", element: <h1>Login</h1> },
33]);

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app