Blog>
Snippets

Implementing Pre-Condition Checks Before Navigation

Show how to use TanStack Router's blocking features to implement pre-condition checks, such as ensuring a user is authenticated before allowing navigation to a protected route.
import { useNavigate, useLocation } from 'react-router-dom';
import { useEffect } from 'react';
import { isAuthenticated } from './auth'; // Suppose this is a function to check if the user is authenticated
Import necessary hooks from TanStack Router (previously known as React Router) and any auth function to check if a user is authenticated.
const ProtectedRoute = ({ children }) => {
  const navigate = useNavigate();
  const location = useLocation();
  
  useEffect(() => {
    if (!isAuthenticated()) {
      // If not authenticated, redirect to login page
      navigate('/login', { state: { from: location }, replace: true });
    }
  }, [navigate, location]);
  
  return isAuthenticated() ? children : null;
};
Defines a ProtectedRoute component that checks if a user is authenticated. If not, it redirects to the login page, preserving the intended destination to return to after login. It renders the children (the protected component) only if the user is authenticated.
export default ProtectedRoute;
Exports the ProtectedRoute component for use in the application.