Blog>
Snippets

Dynamic Role-Based Route Protection

Code example showcasing how to dynamically protect routes and apply role-based access controls using TanStack Router.
import { Navigate, useRoutes } from 'tanstack/react-location';

// Define roles
const roles = {
  ADMIN: 'admin',
  USER: 'user'
};

// Simulate a user authentication status and role
const currentUser = {
  isAuthenticated: true,
  role: roles.ADMIN
};
First, import necessary functions from TanStack Router and define user roles. Then, simulate a current user with authentication status and role.
const ProtectedRoute = ({ children, allowedRoles }) => {
  return currentUser.isAuthenticated && allowedRoles.includes(currentUser.role) ? children : <Navigate to='/login' replace />;
};
Define a ProtectedRoute component that checks if the current user is authenticated and has a role that is included in the allowedRoles array for a particular route. If not, it redirects to the login page.
const routes = [
  { path: '/', element: <Home /> },
  { path: '/login', element: <Login /> },
  { path: '/admin', element: <ProtectedRoute allowedRoles={[roles.ADMIN]}><Admin /></ProtectedRoute> },
  { path: '/user', element: <ProtectedRoute allowedRoles={[roles.USER, roles.ADMIN]}><User /></ProtectedRoute> }
];
Define the app routes. The /admin and /user routes are protected and require the user to have specific roles to access them. The ProtectedRoute component wraps the respective component for these routes.
const AppRoutes = () => {
  const element = useRoutes(routes);
  return <>{element}</>;
};
Define a component that utilizes the useRoutes hook from TanStack Router to render the routes. This approach dynamically applies route protection based on user roles.