next.jsnext-auth

How do you access session.user.id in nextauth?


I am using next-auth version 4.19.2 .

I have a simple component that just displays who they're logged in as:

import { useSession, signIn, signOut } from "next-auth/react"

export default function LoginPlaceholder() {
  const { data: session } = useSession();

  if(session) {
    return <>
    
      Signed in as 
        userID: {session.user.id} <br/>
        name:  {session.user.name} <br/>
        email:  {session.user.email} <br/>
        
      <button onClick={() => signOut()}>Sign out</button>
    </>
  }
  return <>
    Not signed in <br/>
    <button onClick={() => signIn()}>Sign in</button>
  </>
}

My [...nextauth.js] just returns some dummy data:

      async authorize(credentials) {

        console.log("authorize script running...");

        const user = { id: 22, name: 'J Smith', email: 'jsmith@example.com' }
        return user;
      }

For some reason, my output only displays the name and email, but no id.

Signed in as userID:
name: J Smith
email: jsmith@example.com

I work on a project, where multiple people in an organization could share the same email address (not my idea), so email is not a unique identifier for me. I need the either the ID or the username, as a unique identifier, but I was unsure how to get that.

I also tried passing other data, but the only thing I can get to show up is name and email.

const user = { id: 22, userName: 'jSmith' name: 'J Smith', email: 'jsmith@example.com' }

But again, my components are not getting any values for anything other than name and email.

My question is: How do I modify my code to display the username?


Solution

  • You should use callbacks, something along these lines:

        callbacks: {
            async jwt({token, user}) {
          
               if (user?.id) {
                   token.id = user.id
               }
               if (user?.userName) {
                   token.userName = user.userName;
               }
               return token
            },
            async session({session, token}) {
                session.id = token.id;
                session.userName = token.userName;
                return session;
            }
          }