React › Routing

How would you protect certain routes so only logged in users can access them?

Advanced

Answer

You create a wrapper component that checks whether the user is logged in, and either renders the protected page or redirects them to a login page instead, using the Navigate component from React Router. This wrapper is then placed around any route that needs protection.
function ProtectedRoute({ children }) {
  const { user } = useAuth();
  if (!user) return <Navigate to="/login" />;
  return children;
}

<Route path="/dashboard" element={
  <ProtectedRoute><Dashboard /></ProtectedRoute>
} />
Real-world example A banking app automatically redirects any visitor who is not logged in away from the account dashboard page and back to the login screen, using a shared ProtectedRoute wrapper around every sensitive page.

Common follow-ups: How would you also remember the page a user was trying to visit, so they land there after logging in?;How would you protect a route based on a user's role instead of just whether they are logged in?