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
}
}
})
You can do like that in your callback :-
callbacks: {
jwt:({token,user})=>{
if(user){
token.id = user.userId;
}
return token;
},
session:({session,token}) =>{
if(token){
session.user.id = token.id;
}
return session;
}
}
and don't forget to return the user in the function which is executed just before the callback, otherwise it tell undefined.