NextAuth user is undefined in session callback with custom session

I am using NextAuth and CredentialsProvider to login and want to extend the user/session to add a custom field. I overrode my User and Session interfaces. When logging in I am returning a user with the updated model in my authorize() func. My user object in the jwt() callback is valid when I log it, but then seems to immediately run again and undefined is logged. By the time the session() callback is called, the user object is undefined there (I assume because it somehow got set to undefined in the jwt() callback).

I came to the same conclusion as this post and this post, but it feels like this is incorrect. Why do we have to append the user to the token in the jwt() callback when the user is passed into the session() callback? I will attach my code/logs below to see if this helps debug.

Models

declare module "next-auth" {
  interface Session extends DefaultSession {
    user: DefaultSession["user"] & {
      id: string;
      // ...other properties
      username?: string;
      // role: UserRole;
    };
  }

  interface User extends DefaultUser {
    username?: string;
    // ...other properties
    // role: UserRole;
  }
}

Callbacks

callbacks: {
    session({ session, token, user }) {
      console.log("User in session: ", user);
      return {
        ...session,
        user: {
          ...session.user,
          id: token.sub,
          username: user.username,
        },
      };
    },
    jwt({ token, user }) {
      console.log("User in JWT: ", user);
      return { ...token, user };
    },
  },

Logs

User in JWT:  {
  id: 'clqd9un7t0004q9xh76tmqd4e',
  email: null,
  image: null,
  username: 'newuser'
}
User in JWT:  undefined
User in session:  undefined

Leave a Comment