Blog>
Snippets

Implementing Route Guards for Authentication

Provide an example of using route guards with TanStack Router to prevent access to certain areas of an application based on user authentication status.
import { createBrowserRouter, RouterProvider } from 'tanstack/react-router';
First, import the necessary functions from TanStack Router.
const requireAuth = async ({ params }) => {
  // Mocking an auth check
  const isAuthenticated = await checkAuth();
  if (!isAuthenticated) {
    throw new Response(null, { status: 401, statusText: 'Unauthorized' });
  }
};
Define a route guard function `requireAuth` that simulates checking if a user is authenticated. If not, it throws an Error, preventing access.
const checkAuth = () => {
  // Mocked authentication check
  return Promise.resolve(true); // or false to simulate unauthenticated
};
In this example, `checkAuth` is a mocked function that should asynchronously check the user's authentication status.
const router = createBrowserRouter([
  {
    path: '/',
    element: <HomePage />,
    loader: requireAuth
  },
  {
    path: '/login',
    element: <LoginPage />
  }
]);
Create routes with TanStack Router, where the home page route uses `requireAuth` to check if the user can access the route.
function App() {
  return <RouterProvider router={router} />;
}
Finally, integrate the router with your application by rendering `RouterProvider`.