10

I want to update the user's data but after updating the user's data how to make also the change appear in session?

[...nextauth].js

    callbacks: {
    jwt: ({ token, user }) => {
      if (user) {
        token.id = user.id;
        token.name = user.name;
        token.surname = user.surname;
        token.email = user.email;
        token.role = user.role;
      }
      // Here, check the token validity date
      if (token.tokenExpiration < Date.now()) {
        // Call the endpoint where you handle the token refresh for a user
        const user =  axios.post(
          `${process.env.API_URL}/auth/authentication/refresh`,
          {
            refreshToken: token.refreshToken,
          }
        );
        // Check for the result and update the data accordingly
        return { ...token, ...user };
      }
      return token;
    },
    session: ({ session, token }) => {
      if (token) {
        session.id = token.id;
        session.name = token.name;
        session.surname = token.surname;
        session.email = token.email;
        session.role = token.role;
      }
      return session;
    },
  },
  secret: process.env.SECRET_KEY,
  jwt: {
    secret: process.env.SECRET_KEY,
    encryption: true,
    maxAge: 5 * 60 * 1000,
  },

api/user/index.js Here I update the user content, what should I do to update the session object detail

const updateUser = await prisma.user.update({
  where: {
    email: 'test@email.io',
  },
  data: {
    name: 'User',
  },
})

session object

    name  : Company
email : test@email.io
expires : 2022-04-26T18:44:36.424Z
id  : 2
name  : Company
surname : Surname
email : test@email.io
role  : 2
n9p4
  • 304
  • 8
  • 34
  • I have exactly the same problem. What did you do to achieve this? It is driving me crazy – Mario Oct 25 '22 at 23:55

1 Answers1

1

I have the same problem and have a hacky workaround. In the session callback, get the user from the database. This callback is triggered whenever the session is checked (docs), so you can call getSession(), useSession(), or even signIn() somewhere after you update the user.

async function getUserFromDB(accessToken) {
  // I'm not super familiar with prisma but you get the idea
  const user = await prisma.user.findUnique({
    // logic to get user
    // maybe it needs your accessToken
  });
  return user;
}
// [...nextAuth].js
session: ({ session, token }) => {
  if (token) {
    session = await getUserFromDB(token.accessToken);
  }
  return session;
}

Obvious drawback: There is a call to get the user from the database anytime the session is checked.

buckldav
  • 11
  • 3