Search code examples
next.jsjwtnext-authlibspotify

Why user and account object is undefined in Next Auth callback


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


Solution

  • 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