skip to Main Content

I use Next.js and Next-auth for my project.

I’m building a Sidebar component where I want to show a list of items from a user.

So I’m getting the session with useSession.

When I log the session like so…

export default function Sidebar() {
  const { data: session, status } = useSession();

  console.log(session);

  return (
    ...
  )
}

…I get an object including the user object.

But when I try to log the user like so…

export default function Sidebar() {
  const { data: session, status } = useSession();

  console.log(session.user);

  return (
    ...
  )
}

I get this error:

TypeError: Cannot read properties of undefined (reading ‘user’)

Any idea what’s the problem here?

Thanks a lot,
Gabriel

2

Answers


  1. As useSession is a hook, it will make data available asynchronously. Hence, you need to check if session is not undefined before logging it/ using it.

    console.log(session?.user);
    

    or

    if(session) {
      console.log(session.user);
    }
    
    Login or Signup to reply.
  2. The problem may be in the deconstruction of the object.
    And it’s recommended you check if it’s not null, just like Rameez said.
    Try this:

    const { data, status } = useSession();
    
    if(data.session.user){
        console.log(data.session.user);
    }
    
    return (
        ...
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search