How would you use a higher order component to add authentication protection to a page?
Short answer
A withAuth higher order component can check whether a user is logged in, and either render the actual protected page or redirect them to a login page instead. This lets you protect many different pages using the exact same wrapping logic.
Advertisement
AModel answer
A withAuth higher order component can check whether a user is logged in, and either render the actual protected page or redirect them to a login page instead. This lets you protect many different pages using the exact same wrapping logic.
function withAuth(WrappedComponent) {
return function ProtectedRoute(props) {
const { user } = useAuth();
if (!user) return <Navigate to="/login" />;
return <WrappedComponent {...props} />;
};
}
const ProtectedDashboard = withAuth(Dashboard);Real-world example
An admin panel wraps every sensitive page, like billing and settings, with the same withAuth higher order component, so a user who is not logged in is automatically redirected to the login page instead of seeing protected content.
Likely follow-ups
- How would you achieve the same protection using a custom hook instead of a higher order component?
- What happens if you wrap a component with multiple higher order components at once?
Related topics