Blog>
Snippets

Implementing Route Guards with TanStack Router

Show how to create route guards in TanStack Router to protect private routes, using hooks for authentication checking and redirecting unauthorized users.
import { Navigate } from 'tanstack-router';
Import Navigate component from tanstack-router for redirection.
// Simulated authentication hook
function useAuth() {
  const user = { loggedIn: false };
  return user && user.loggedIn;
}
A simulated hook (useAuth) to check if the user is authenticated. It returns true if the user is logged in.
// Route guard component
cnst RequireAuth = ({ children }) => {
  const isAuthenticated = useAuth();
  return isAuthenticated ? children : <Navigate to="/login" replace />;
};
A Route Guard component (RequireAuth) that uses the useAuth hook to determine if the user is authenticated. If not authenticated, it redirects to the login page.
// Usage inside route definitions
const routes = [
  {
    path: '/private',
    element: <RequireAuth><PrivatePage /></RequireAuth>
  },
  {
    path: '/login',
    element: <LoginPage />
  }
];
Demonstrating how to use the RequireAuth component in route definitions to protect a private route. Unauthorized users trying to access the '/private' route will be redirected to '/login'.