React › Routing
How would you protect certain routes so only logged in users can access them?
AdvancedAnswer
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.