next.jsnext-auth

How can I update the Session info on Every Refresh?


I have an admin portal where the admin can edit other users' names. However, if a user is already logged in with the name "John" and their name is updated to "Michael," the change doesn't reflect properly in NextAuth session.


Solution

  • In nextauth route on auth options route ,try adding following callbacks, here for each page/api call from server, refresh token will updated with latest user name from db.

    const authOptions = {
    //other configurations
    callbacks: {
        async session({ session, token }: { session: Session; token: JWT }) {
          if (session.user) {
            session.user.name = token.name;
          }
          return session;
        },
        async jwt({ token, user }: { token: JWT; user: User }) {
          if (token && token.email) {
            // add your function instead of following
            const user = await getUserForLogin(token.email);
            //make sure to handle negative scenarios
            token.name = user.name;
          }
          return token;
        },
      },
    
    
    }