Why user and account object is undefined in Next Auth callback

1.5k views Asked by At

I was trying to console log session.user.accessToken and clientsecret which turned out to be undefined, so i headed towards NextAuth.js to see if there's problem, it seems account and user is undefined in jwt callback function

while console.log(account) which is undefined,were did i go wrong?

this is my [...Nextauth].js file

export default NextAuth({
  // Configure one or more authentication providers
  providers: [
    SpotifyProvider({
      clientId: process.env.NEXT_PUBLIC_CLIENT_ID,
      clientSecret: process.env.NEXT_PUBLIC_CLIENT_SECRET,
      authorization: LOGIN_URL
    })
    // ...add more providers here
  ],

  secret: process.env.JWT_SECRET,
  pages: {
    login: "/login"
  },
  callbacks: {
    async jwt({ token, account, user, profile }) {
      //initial user sign in

      if (account && user) {
        console.log({ token, user, account, profile });
        return {
          ...token,
          accessToken: account.access_Token,
          refreshToken: account.refresh_token,
          username: account.providerAccountId,
          accessTokenExpires: account.expires_at * 1000 //handle expiry time in ms
        };
      }
      //return the previous token if current token is expired

      if (Date.now() < token.accessTokenExpires) {
        console.log("Existing token is valid");
        return token;
      }

      //refresh token
      console.log("Existing token has expired");
      return await refreshAccessToken(token);
    },

    async session({ session, token }) {
      session.user.accessToken = token.accessToken;
      session.user.refreshToken = token.refreshToken;
      session.user.username = token.username;
      return session;
    }
  }
});

2

There are 2 answers

3
Jelena On BEST ANSWER

You can examine further in console. For example, in [...nextauth].js add something like:

events: {
    signIn(message) {
      console.log('signin message', message)
    },
    session(){...},
    signOut(message) {
      console.log(message)
    },
  },

  // Enable debug messages in the console if you are having problems
  debug: true,

Reference: https://next-auth.js.org/configuration/events

0
Richard CDSP On

As per the documentation for jwt callback:

The arguments user, account, profile and isNewUser are only passed the first time this callback is called on a new session, after the user signs in. In subsequent calls, only token will be available.

You will only be able to access user, account, and profile at sign-in, so you would need to check if they are defined and use them to add whatever you need from them to the token, since subsequent calls to this callback (including session callback triggered by getSession or getServerSession) will only have the token available.