Blog>
Snippets

Dynamic Navigation Guards Based on User Roles

Provide an example of setting up dynamic navigation guards that block or allow navigation based on the user’s role, using TanStack Router's blocking features.
import { createBrowserRouter, RouterProvider, Route, redirect } from 'react-router-dom';
Importing necessary components from TanStack Router to setup the router, routes, and redirection.
const checkUserRole = async ({ request }) => {
  const userRole = await getUserRoleFromToken(request);
  return userRole;
};
Defining an asynchronous function to mock fetching a user's role from a token. In a real application, you would replace this with your actual logic for retrieving the user's role, probably from an authentication token.
const adminRouteGuard = async ({ request }) => {
  const userRole = await checkUserRole({ request });
  if (userRole !== 'admin') return redirect('/unauthorized');
};
Setting up a route guard for admin routes. It uses the checkUserRole function to determine if the user is an admin. If not, the user is redirected to an unauthorized route.
const router = createBrowserRouter([
  {
    path: '/',
    element: <HomePage />
  },
  {
    path: '/admin',
    element: <AdminPage />,
    loader: adminRouteGuard
  },
  {
    path: '/unauthorized',
    element: <UnauthorizedPage />
  }
]);
Creating the browser router instance and defining routes. The '/admin' route uses the adminRouteGuard to protect the route. If the user is not an admin, they will be redirected to '/unauthorized'.
<RouterProvider router={router} />
The RouterProvider component from TanStack Router is used to wrap the application's component tree, passing in the router instance as its prop.