I have an small application that is using next-auth that shows a signin/signout button depending if the user is signed in or not. The buttons works as intended and redirects me to the signinpage when clicked.
But how do I automaticly redirect to the signin-page if not signed in ?
I have tried adding signIn() under the if(session)... but that gives me the error:
ReferenceError: window is not defined
and also router.push('/api/auth/signin) but that gives me the 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>
</>
);
}