DEV Community

Vamshi Krishna
Vamshi Krishna

Posted on

User if they are already logged in. Can't open Login Page in Next.js

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;
```

`
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay