#Extending user object in jwt session

1 messages · Page 1 of 1 (latest)

magic ibex
#

It's my first time implementing NextAuth, maybe it's something simple I'm missing. The documentation doesn't help me though and in the forum no one is answering. I would really appreciate some help 🙏

#

Extending user object in jwt session

dapper umbra
#

do u use ts?

magic ibex
#

yes

dapper umbra
#

try extending type in global type like this

declare module 'next-auth' {
   interface User {
      /// add types for default user
    }
    interface Session {
        user: {
            // add types for user stored in session

        } & DefaultUser 
    } 
   
}
magic ibex
#

import type { DefaultUser } from "next-auth" doesn't work for me

#

Ah, but import type { User } .. will do

dapper umbra
#

do u pass it in jwt/session callback?

magic ibex
#

I am doing this now:

async jwt({ token, user }) {
      if (user) {
        token.user = user;
      }
      return token;
    },

And I manage to read it the first time it gets called!

#

But its called multiple times and then the user in the jwt callback becomes undefined

#

And it's still not in the auth() response in my server action

#

Okay, I got (not sure if thats how one should do it though)

I am using the session callback to get the user object from the token and then store it there.

async session({ session, token }) {
      if (token.user) {
        session.user = token.user;
      }
      return session;
    },
dapper umbra
#

thats how i do it

#
 callbacks:{
        jwt: async ({ token, user, account }) => {
            if(account) {
                token = {...token, ...account}
            }
            if (user) {
              token = { ...token, ...user };
            }
            return token;
          },
          session: async ({ session, token }) => {
            if (session.user) {
              session.user = {
                ...session.user,
                ...token,
              };
            }

            return session;
          },
    },
#

i use account cuz im using diffrent providers

magic ibex
#

hmm i see, so this should be stable

#

thank you!