'Get User ID from session in next-auth client

I'm using next-auth with Prisma and Graphql, I followed these instructions to set up the adapter and my models accordingly: https://next-auth.js.org/adapters/prisma Authentication works but when I inspect session object from here : const { data: session, status } = useSession() I don't see ID enter image description here

The reason I need the ID is to make further GraphQL queries. I'm using email value for now to fetch the User by email, but having ID available would be a better option.



Solution 1:[1]

Here's the quickest solution to your question:

src/pages/api/auth/[...nextAuth].js

export default NextAuth({
  ...
  callbacks: {
    session: async ({ session, token }) => {
      if (session?.user) {
        session.user.id = token.uid;
      }
      return session;
    },
    jwt: async ({ user, token }) => {
      if (user) {
        token.uid = user.id;
      }
      return token;
    },
  },
  session: {
    strategy: 'jwt',
  },
  ...
});

Solution 2:[2]

I believe you can change the callbacks so it includes the user's ID in the session: https://next-auth.js.org/configuration/callbacks.

You will need to change the JWT callback so it also include the userId and the session callback so the id is also persisted to the browser session.

Solution 3:[3]

This worked for me.

callbacks: {
    async jwt({ token, user, account, profile, isNewUser }) {
        user && (token.user = user)
        return token
      },
    async session({ session, token, user }) {
        session = {
            ...session,
            user: {
                id: user.id,
                ...session.user
            }
        }
        return session
      }
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 kohane15
Solution 2 Kenneth Van den Berghe
Solution 3 Gautam Ghai