How can I update the Next Auth Session every time a page reloads by getting data from API?

420 views Asked by At

I have a situation where I have to update Next Auth Session every time a page reloads so that the "Users" Details can be updated.

I need to call API each time a page reloads to get the Users data and then update Next Auth Session.

1

There are 1 answers

0
eroironico On

Next Auth provides a session callback so that you can use it to execute some code every time the session gets requested. What i'd do is:

// config.js

// ..rest of config
callbacks: {
    session: async ({ session, token: userFromJWT }) => {
      delete userFromJWT.password;

      const updatedSession = {
        ...session,
        user: {
          ...userFromJWT,
        },
      }

      const getUpdatedData = async () => {
          // do stuff
      }

      const data = await getUpdatedData();
      
      // check data
      // here you can alter the `updatedSession` object to return whatever you want
      // E.G.: updatedSession.error = "some error"

      return updatedSession
    },
    jwt: ({
      token: userFromJWT,
      user: userFromAuth,
      session: userFromUpdate,
    }) =>
      // if `userFromAuth` has a value it means the user has just logged in
      userFromAuth
        ? userFromAuth
        : {
            ...userFromJWT,
            // `userFromUpdate` will be anything returned by the `session` callback
            ...userFromUpdate,
          },
  },