Next.js Discord

Discord Forum

Can't access session user values with NextAuth session.

Answered
KlaasPeters posted this in #help-forum
Open in Discord
I am a beginner React developer student and I have a problem I don't seem to solve.

I am reading the following documentation, the part of useSession(): https://next-auth.js.org/getting-started/client#usesession
Only, something is wrong, I can't get the user value from {session.user.email} whit the following code:

export default function Profile() {
  const { data: session, status } = useSession()
  console.log(session.user.email);

  return (
    <LayoutIndex>
      <section className="container mx-auto text-center py-20">
        <h3 className="text-4xl font-bold text-white"></h3>
        <br />
        <br />
        <Link className="mt-5 px-10 py-1 rounded-sm bg-indigo-500 text-gray-50" href={'/'}>Go to homepage</Link>
      </section>

    </LayoutIndex>
  )
}

export async function getServerSideProps({ req }) {
  const session = await getSession({ req })

  if (!session) {
    return {
      redirect: {
        destination: '/login',
        permanent: false
      }
    }
  }

  return {
    props: { session }
  }
}


Then it gives the following error:
 error Error [TypeError]: Cannot read properties of undefined (reading 'user')

 
   7 | export default function Profile() {
   8 |   const { data: session, status } = useSession()
>  9 |   console.log(session.user.email);
                   ^ 


I don't understand what is wrong, because if I console.log(session) I have the following output:
{
  "user": {
    "email": "test1234@gmail.com"
  },
  "expires": "2023-08-17T06:21:19.973Z"
}


Anyone have an idea why I cant access session.user?
Answered by KlaasPeters
Okay, I solved it with first asking if a session exist with if (session). So the code is now:
export default function Profile() {
  const { data: session, status } = useSession()
  if (session) {
    console.log(session.user.email);
  }

This works! Sorry for bothering the help forum with it.

Kind regards,
Klaas
View full answer

2 Replies

here a screenshot of the output of console.log(session)
Okay, I solved it with first asking if a session exist with if (session). So the code is now:
export default function Profile() {
  const { data: session, status } = useSession()
  if (session) {
    console.log(session.user.email);
  }

This works! Sorry for bothering the help forum with it.

Kind regards,
Klaas
Answer