Next.js Authentication using Higher-Order Components
Higher-Order Components (HOCs) are a powerful pattern for authentication in Next.js.
The Problem
Authentication logic often gets scattered across components, making it hard to maintain.
The HOC Solution
function withAuth<P extends object>(WrappedComponent: React.ComponentType<P>) {
return function AuthenticatedComponent(props: P) {
const { data: session, status } = useSession();
if (status === 'loading') return <Loading />;
if (!session) return <SignIn />;
return <WrappedComponent {...props} />;
};
}
Benefits
- Colocation of auth logic
- Type-safe
- Reusable across pages
Conclusion
HOCs provide a clean way to handle authentication in Next.js.
