Search code examples
next.jsnext-auth

Why can't I access Session data that exists before the return statement in NextJs page


Trying to understand how this works.

I have a Session present in NextJS. I can access that inside the page view no problem.

But If I try to access any of that data before the return statement, it comes back undefined, even though the variables are in the page when it renders.

Can anyone tell me why this is?

Sample code from a page

const { data: session } = useSession();

if(session) { // Never runs, always evaluates as false
  console.log("USER ID : " + session.userId); 
}
console.log("USER ID : " + session?.userId); // Undefined
// @ts-ignore
if(session) {
  return (
    <>
      <div className="min-h-full">
        <nav className="bg-fadedFadedPurple">
          <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div className="flex items-center justify-between h-16 w-full">
              <div className="flex items-center w-full h-full">
                <div className="flex-shrink-0">
/*perfectly fine*/  <Link className="hover:cursor-pointer" href={`/app/${session.userId}/dashboard`}>

Solution

  • useSession in Next.js is only defined after an initial loading state see: https://next-auth.js.org/getting-started/client#example-1

    you are trying to check the session before this loading state so it is undefined and does not hit your conditions.

    Later when it is rendering in your page the hook gets the session as its past the initial loading state

    this is what you are trying to do, but require a callback to when the state is loaded

         const session = useSession({
                required: true,
                onUnauthenticated() {
                // The user is not authenticated, handle it here.
                },
            })
    
            if (status === "loading") {
                //if(session) { //this is your Undefined
                console.log("USER ID : " + session?.userId); 
                //}
                return "Loading or not authenticated..."
            }
            //if(session) { // this is if the session has been loaded
              console.log("USER ID : " + session.userId); 
            //}
    
            return "User is logged in"
        }
    

    further if you want the session youll have to await a call

       const session = await getSession()
    

    as per the documentation https://next-auth.js.org/getting-started/client#getsession

    hope this helps you understand why your code isnt working