@inertiapixel/nextjs-auth
Version:
Authentication system for Next.js. Supports credentials and social login, JWT token management, and lifecycle hooks — designed to integrate with nodejs-auth for full-stack MERN apps.
33 lines (32 loc) • 1.55 kB
JavaScript
//src/hoc/withAuth.tsx
'use client';
import { jsx as _jsx } from "react/jsx-runtime";
import { useAuth } from '../hooks/useAuth';
/**
* Higher-Order Component that protects a page/component by requiring authentication.
* It leverages the `useAuth` hook, so all redirect logic is centralized there.
*
* @example
* const OrdersPage = () => <div>Orders</div>;
* export const ProtectedOrdersPage = withAuth(OrdersPage);
*/
export const withAuth = (WrappedComponent) => {
const AuthenticatedComponent = (props) => {
// Pull state from the central auth hook
const { isAuthenticated, loading, isLoaded } = useAuth();
// While the auth state is resolving, show a minimal loader.
if (loading || !isLoaded) {
return (_jsx("div", { className: "flex h-screen w-full items-center justify-center", children: _jsx("span", { className: "animate-spin rounded-full border-2 border-t-transparent h-8 w-8" }) }));
}
// If the user is not authenticated, `useAuth` will already have kicked off a redirect.
// We render `null` to avoid flashing protected content while that happens.
if (!isAuthenticated) {
return null;
}
// All good—render the protected component.
return _jsx(WrappedComponent, { ...props });
};
// Give the HOC a helpful display name for React DevTools.
AuthenticatedComponent.displayName = `withAuth(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
return AuthenticatedComponent;
};