Next.js Discord

Discord Forum

useSession's update method not updating the session.

Unanswered
Bigheaded ant posted this in #help-forum
Open in Discord
Bigheaded antOP
I have added an active property to my next auth jwt tokken and session. The active property exists on user object which lives on database. Upon email confirmation, I update the active property to be true then I run update() method returned by useSession() to update the session.

This is the official way of updating the session in NextAuth : https://next-auth.js.org/getting-started/client#updating-the-session

The problem is my session object still contains old active value which is false.

It only updates if I log out and login again. Can someone point out what I am doing wrong here?

Here is my code which calls update method.

    verifyToken(token as string)
      .then(() => {
        setStatus("verified");

        // Update session to fetch latest user information
        if (session && session.status === "authenticated") {
          session.update();
          console.log("Update the session");
        }
      })
      .catch(() => setStatus("invalid"));

7 Replies

Bigheaded antOP
bump
someone help please.
Southern African anchovy
this is tricky, but I finally got it
Southern African anchovy
first off, when you call update() you can pass arbitrary data:
update({my_custom_field: "Monkey"})

Then in the jtw callback in your auth options assign the data to the token
...
callbacks: {
  ...
  async jwt({token, trigger, session}) {
    // session is your data, so we need to put
    // that data in the token
    if (trigger === "update" && session?.my_custom_field !== undefined)
       token.my_custom_field = session.my_custom_field;    
  }
  ...
}

Then in the session callback, pull that field from the token

...
callbacks: {
  ...
  async session({session, token}) {
    session.my_custom_field = token.my_custom_field;
    return session;
  }
  ...
}
Bigheaded antOP
Hi, thanks for the repsonse.

But in my case, I had to refetch latest user details insdie if (trigger === "update") block and overwrite current token with new data.
Southern African anchovy
Glad you got it sorted
Southern African anchovy
I learnt one other thing, if you have a server component relying on session state, then you need to use router.refresh() to refresh the server components.