Here is an example of how you can create a private route in Next.js:
First, create a higher-order component (HOC) that will check if the user is authenticated before rendering the protected route component:
import { useEffect, useState } from 'react';
import Router from 'next/router';
const withAuth = (WrappedComponent) => {
const WithAuth = (props) => {
const [loading, setLoading] = useState(true);
const [user, setUser] = useState(null);
useEffect(() => {
// Fetch user data here and set it using setUser
// For example:
// setUser(fetchUserData());
setLoading(false);
}, []);
if (loading) {
return <div>Loading...</div>;
}
if (!user) {
Router.push('/login');
return null;
}
return <WrappedComponent {...props} />;
};
WithAuth.getInitialProps = async (ctx) => {
const wrappedComponentInitialProps = WrappedComponent.getInitialProps
? await WrappedComponent.getInitialProps(ctx)
: {};
return { ...wrappedComponentInitialProps };
};
return WithAuth;
};
export default withAuth;
Then, use the withAuth HOC to wrap the protected route component:
import withAuth from '../hoc/withAuth';
const ProtectedRoute = (props) => {
return <div>This is a protected route</div>;
};
export default withAuth(ProtectedRoute);
Finally, use the protected route component in your Next.js app as you would any other route:
import ProtectedRoute from '../components/ProtectedRoute';
const Home = () => {
return (
<div>
<ProtectedRoute />
</div>
);
};
export default Home;
This is just one way to implement private routes in Next.js, but it should give you an idea of how it can be done.