Search code examples
next.jsnext-auth

getting Account as undefined in the Next Auth Jwt Callback function


I am using Next Auth V4 (upgraded from v3 - i.e. did not implement v4 from scratch).

I am trying to fetch the user data that are coming from my okta provider in the account object in the sign in callback, but it gets unset/undefined when I try to use it in the jwt and session callback functions.

Here are the Next Auth Configs:

jwt: {
    secret: process.env.NEXT_AUTH_SECRET,
    encode, // function to encode the claims
    decode  // function to validate the token and decode the claims
  },
...
  session: {
    maxAge: process.env.SESSION_TIMEOUT || 900,
    updateAge: process.env.SESSION_UPDATE_TIMEOUT || 60,
    strategy: "jwt",
  },
...
  providers: [
    OktaProvider({
      clientId: process.env.OKTA_CLIENT_ID,
      clientSecret: process.env.OKTA_CLIENT_SECRET,
      domain: process.env.OKTA_DOMAIN,
      issuer: process.env.OKTA_ISSUER
    })
  ],
...
 callbacks: {
   ...
   async jwt({ token, user, account, profile, isNewUser}){
    // here other then token, everything is undefined.
    return token
   }
   ...
   async session({ session, token}) {
     return session
   }


Solution

  • If this still actual for you. My problem was in 'next-auth.d.ts', I renamed it to nextaut.d.ts and add this code

    import NextAuth, { DefaultSession } from 'next-auth';
    import { User, Session } from 'next-auth';
    import { DefaultJWT } from 'next-auth/jwt';
    
    declare module 'next-auth' {
      /**
       * Returned by `useSession`, `getSession` and received as a prop on the `SessionProvider` React Context
       */
      interface Session extends DefaultSession {
        gqlToken: string;
        accessToken: string;
        refreshToken: string;
      }
    }
    
    declare module 'next-auth/jwt' {
      interface JWT extends DefaultJWT {
        gqlToken: string;
        accessToken: string;
        refreshToken: string;
      }
    }