Composing High Order Components for Page Authentication
Implement a higher-order component in Next.js 14 to wrap pages with authentication logic, redirecting unauthenticated users.
import { useRouter } from 'next/router';
import React, { useEffect } from 'react';
// Redirects to '/login' if not authenticated
function withAuth(WrappedComponent) {
return function (props) {
const router = useRouter();
// Simulate authentication logic
const isAuthenticated = false; // Replace with actual auth logic
useEffect(() => {
if (!isAuthenticated) router.push('/login');
}, [isAuthenticated, router]);
// Render nothing while authentication status is being verified
if (!isAuthenticated) return null;
// Render the wrapped component with all the passed props
return <WrappedComponent {...props} />;
};
}
export default withAuth;
This code snippet creates a higher-order component (HOC) named 'withAuth' that can wrap any React component. This HOC checks for whether a user is authenticated and, if not, redirects the user to a '/login' page. The 'isAuthenticated' variable simulates the authentication logic and should be replaced with the real authentication check. If the user is not authenticated, 'useEffect' redirects to the login page, and the component returns null, which means nothing is rendered until the authentication status is verified. If authenticated, the HOC renders the wrapped component (WrappedComponent) with all of its props.