2

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>
    </> 
  );
}
Burton
  • 407
  • 1
  • 6
  • 19

2 Answers2

4

You need to put the code in useEffect that way it only gets executed on the client when the component mounts. Also, you need to wait untill the loading variable becomes false only then you should check the session variable.

useEffect(()=>{
  if(!loading){
    if (session) {
      console.log("session = true")
      router.push('/blogs')
    }else{
      // maybe go to login page
      router.push('/login')
  }
 }
},[router,session])

Also, take a look at the How to protect routes in Next.js next-auth? for a complete solution with login and logout pages.

Ivan V.
  • 7,593
  • 2
  • 36
  • 53
0

For those Googling like mad trying to figure this out, here's how I did it.

Within your component file:

import { useEffect} from "react";
import { useSession } from "next-auth/react";
import { signIn} from "next-auth/react";

export const myComponent = () => {
    
    const { data: sessionData } = useSession();
    const { status: sessionStatus } = useSession();
    
    useEffect(() => {            
        console.log(sessionStatus);
        if (sessionStatus === "unauthenticated") {
            void signIn('azure-ad'); //Add your own provider here
        }              
    }, [sessionStatus])

    //Other component code

}

Your page will render client-side and will start to load the session. Initially, the status will be "loading", you don't handle this specifically. After a second or two, the status will switch to either "authenticated" or "unauthenticated", at which point you can action it. If you just want to redirect the user if they're not logged in, then call the signIn function.

You need to add some controls in your page so that sensitive data, buttons, etc. are disabled if sessionStatus !== "authenticated", as the page will be rendered and visible.