Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did user object is undefined in NextAuth session callback?

I use NextAuth for signIn with discord provider and I need to add userID into the session object. For that I use session callback but user object is undefined. When I try to add userID to the session object, I got an error like this :

[next-auth][error][JWT_SESSION_ERROR] https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'id')

Indeed, it seems the user object is undefined but I don't have any solution.

export default NextAuth({
  providers: [
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID,
      clientSecret: process.env.DISCORD_CLIENT_SECRET,
      authorization: { params: { scope: 'identify' } }
    })
  ],
  session: {
    jwt: true
  },
  jwt: {
    secret: process.env.JWT_SECRET
  },
  callbacks: {
    async session({session, user}) {
      session.user.id = user.id
      return session
    },
    async jwt(token) {
      return token
    }
  }
})
like image 212
Theo Avatar asked May 22 '26 01:05

Theo


1 Answers

You can do it like that

    providers: [ 
        Github({
            clientId: process.env.GITHUB_ID,
            clientSecret:process.env.GITHUB_SECRET,
        })
    ],
    database :process.env.DB_URL,
    session:{
        jwt:true
    },
    adapter: MongoDBAdapter(clientPromise, {
        databaseName: 'AuthDb'
      }),
    jwt:{
        secret: 'secretCode',
    },
    callbacks:{
        async jwt({token,user}){
            if(user){
                token.id = user.id
            }
            return token
        },
        async session(session,token) {
            session.user.id =token.id
            return session 
        }
    },
}); ```
like image 142
Murad Zeynallı Avatar answered May 23 '26 13:05

Murad Zeynallı



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!