Search code examples
authenticationnext.jsserver-side-renderingnext-auth

NextAuth with GoolgeProvider does not return the user in session callback


Suddenly I can no longer access the email address of the registered user. I use NextAuth and Google as the provider. Up until now, everything has worked. Actually, after successful registration, the e-mail of the user should be delivered by Google. In the MongoDB database, the users table is created as usual and the user is saved there with email. So it must have something to do with NextAuth. Because in the session callback function, I get undefined at session.user

export const authOptions: NextAuthOptions = {
adapter: MongoDBAdapter(clientPromise),

providers:[
    GoogleProvider({
        clientId: process.env.GOOGLE_CLIENT_ID!!,
        clientSecret: process.env.GOOGLE_CLIENT_SECRET!!,
       
      })
],callbacks: {
    async jwt({ token, account, user }) {
          
      if (account) {      
      
        token.accessToken = await SignToken(user.email as string)
        token.id = user.id
      }
      return token
    }, 
    async session({ session, token, user }) {

      session.user = token
     //session.user is undefined
      console.log(session.user)
        return session
      },    
  },
}

Client Side Page:

  const { data: session, status } = useSession()

   if (session) {
    console.log({ session });
   }

Output no Email etc.

enter image description here


Solution

  • you are missing this in authOptions

    session: {
        strategy: "jwt",
      },
    

    if you hover it, you see this

    Choose how you want to save the user session. The default is "jwt", an encrypted JWT (JWE) in the session cookie.

    If you use an adapter however, we default it to "database" instead. You can still force a JWT session by explicitly defining "jwt".