Next.js Authentication using Higher-Order Components
nextjsauth

Next.js Authentication using Higher-Order Components

Solve problems such as colocation, and error-prone code.

March 10, 2023·7 min·1,800 views·56 reactions·Website

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.

“

Hope you enjoyed reading.
If this article helped you, consider sharing it with other developers.

AI Companion

Ask questions about this article

Powered by Sant.AI — coming soon