How to mutate user's session in nextauth when you change user data?
Asked Answered
M

1

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: '[email protected]',
  },
  data: {
    name: 'User',
  },
})

session object

    name  : Company
email : [email protected]
expires : 2022-04-26T18:44:36.424Z
id  : 2
name  : Company
surname : Surname
email : [email protected]
role  : 2
Mite answered 27/3, 2022 at 18:46 Comment(1)
I have exactly the same problem. What did you do to achieve this? It is driving me crazyHierogram
S
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.

Snider answered 11/12, 2022 at 4:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.