Course contentsShow
← React
Lesson 1871 of 2,39643. RoutingFree lesson

Role-Based Authorization

Extending protection beyond logged-in/out to check user roles or permissions before allowing route access.

Role-Based Authorization

What you'll learn: How to protect routes not just by login status, but by checking whether a user has the right role or permissions to access specific pages.

Beyond Simple Authentication

You've already learned how to block routes based on whether someone is logged in. But real applications need finer control: an admin dashboard shouldn't be accessible to regular users, even if they're authenticated. A manager might see features that employees can't.

Role-based authorization extends your protection logic to check who the user is, not just that they're logged in.

The Pattern

Think of it like security clearance levels. Being in the building (authenticated) isn't enough—you need the right badge level (role) to enter certain rooms (routes).

In your loader or wrapper component, check the user's role against requirements:

// In a loader
export async function adminLoader({ request }) {
  const user = await getCurrentUser();
  
  if (!user) {
    throw redirect('/login');
  }
  
  if (user.role !== 'admin') {
    // User is logged in but lacks permission
    throw redirect('/unauthorized');
  }
  
  return { user };
}

Or as a wrapper component pattern:

function RoleProtectedRoute({ children, requiredRole }) {
  const user = useAuth();
  const navigate = useNavigate();
  
  if (!user) {
    return <Navigate to="/login" />;
  }
  
  if (user.role !== requiredRole) {
    return <Navigate to="/unauthorized" />;
  }
  
  return children;
}

You can check single roles, arrays of allowed roles, or granular permissions (like "canEditPosts"). The key is separating the authentication check ("are you logged in?") from the authorization check ("are you allowed to do this?").

Key Takeaway: Role-based authorization adds a second layer of protection by verifying user permissions, not just login status, ensuring sensitive routes are only accessible to users with the appropriate role or privilege level.