To prevent a logged-in user from accessing the login page in Next.js, you can create a custom _app.js file and use the useEffect hook to redirect the user if they are already logged in.
import { useEffect } from "react";
import { useRouter } from "next/router";
import { useAuth } from "../hooks/auth"; // your authentication hook
function MyApp({ Component, pageProps }) {
const { user } = useAuth(); // get the user from your authentication hook
const router = useRouter();
useEffect(() => {
if (user) {
router.push("/dashboard"); // redirect to the dashboard page if the user is already logged in
}
}, [user, router]);
return <Component {...pageProps} />;
}
export default MyApp;
```
`
Top comments (0)