Blog>
Snippets

Configuring Basic Authentication in TanStack Router

Demonstrate how to set up basic authentication checks in TanStack Router to protect a route.
import { createBrowserRouter, RouterProvider } from '@tanstack/react-router';
First, import the necessary components from the TanStack Router package.
async function authLoader({ request }) {
  const user = await getUserFromSession(request);
  if (!user) {
    throw new Response('Unauthorized', { status: 401 });
  }
  return { user };
}
Define an asynchronous loader function, authLoader, to verify if a user is authenticated via session information. If not, it throws an unauthorized response.
const router = createBrowserRouter([
  {
    path: '/',
    element: <PublicComponent />, // Your public component
    errorElement: <ErrorComponent /> // Error handling component for unauthorized access
  },
  {
    path: '/protected',
    element: <PrivateComponent />, // Your protected component
    loader: authLoader,
    errorElement: <ErrorComponent /> // Error handling component
  }
]);
Create the router configuration, including both public and protected routes. The protected route utilizes the authLoader to ensure the user is authenticated.
function App() {
  return <RouterProvider router={router} />;
}
Define your App component where the RouterProvider is used to pass in the router instance, integrating the routing setup into your application.