I have a small application that utilizes next-auth to display a signin/signout button based on the user's sign-in status. The buttons function correctly and redirect me to the signin page when clicked.
However, I am wondering how can I automatically redirect to the signin page if not signed in?
I attempted to add signIn()
within the if(session)...
block, but this resulted in the error:
ReferenceError: window is not defined
I also tried using router.push('/api/auth/signin')
, but encountered the following error:
Error: No router instance found. You should only use "next/router" inside the client-side of your app. https://nextjs.org/docs/messages/no-router-instance
import React from "react";
import { useSession, signIn, signOut } from "next-auth/client";
import { useRouter } from 'next/router'
export default function Home() {
const [session, loading] = useSession();
const router = useRouter()
if (session) {
console.log("session = true")
router.push('/blogs')
return (
<>
Signed in as {session.user.name} <br />
<button onClick={() => signOut()}>Sign out</button>
</>
);
}
console.log("session = false")
return (
<>
Not signed in <br />
<button onClick={() => signIn()}>Sign in</button>
</>
);
}