Higher Order Function with Auth

The withAuth higher-order function simplifies protecting React components with authentication logic. It wraps your components and handles authentication checks centrally, eliminating repetitive code across your application.

Features & Benefits:

  • Centralizes authentication logic in one place
  • Redirects unauthenticated users automatically
  • Provides the user object directly to protected components
  • Offers customizable redirect paths and loading states
  • Maintains consistent authentication behavior throughout your app
  • Includes TypeScript support for type safety

Use it to quickly protect any component that requires authentication:

const ProtectedDashboard = withAuth(Dashboard, {
redirectPath: '/signin',
loadingComponent: <LoadingSpinner />,
});
export type WithAuthProps = {
user: User;
};
export type AuthOptions = {
redirectPath?: string;
loadingComponent?: React.ReactNode;
}
export function withAuth<P extends WithAuthProps>(
Component: React.ComponentType<P>,
options: AuthOptions = {}
){
const { redirectPath = '/login', loadingComponent = null } = options;
const wrappedComponentName = Component.displayName || Component.name || 'Component';
async function AuthProtectedComponent(props: Omit<P, keyof WithAuthProps>) {
try {
const currentUser = await fetchUser();
if (!currentUser) {
redirect(redirectPath);
return null;
}
const combinedProps = {
...props,
user: currentUser
} as P;
return <Component {...combinedProps} />;
} catch (error) {
console.error('Authentication error:', error);
redirect(redirectPath);
return null;
}
}
AuthProtectedComponent.displayName = `withAuth(${wrappedComponentName})`;
return AuthProtectedComponent;
}