Adding custom value to NextAuth session - [next-auth][error][JWT_SESSION_ERROR]

I am trying to add a username field to my NextAuth session data in my t3 app and am getting the following error: https://next-auth.js.org/errors#jwt_session_error Cannot read properties of undefined (reading 'username')

I have added an optional username field to both my User and Session overrides like this:

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;
  }
}


And here are my session and jwt callbacks:
callbacks: {
    session({ session, token, user }) {
      return {
        ...session,
        user: {
          ...session.user,
          id: token.sub,
          username: user.username,
        },
      };
    },
    jwt({ token, user }) {
      console.log("USER: ", user);
      return { ...token, user };
    },
  },


The strange part is the log in the jwt callback logs the correct user obejct (with the username) once, then logs undefined, and then logs the error above. Any idea why my user would be getting set to undefined and passed into the jwt callback? (logs below)

USER:  {
  id: ${userIdFromDb},
  email: null,
  image: null,
  username: 'newuser'
}
USER:  undefined
[next-auth][error][JWT_SESSION_ERROR] 
Was this page helpful?