Refresh id token/user object in React application

Hi!
I am using the @auth0/auth0-react SDK (which has been very nice and easy to use), but I am running into an instance that I’m not sure the best course of action for. I have a ReactJS front end and NodeJS back end, and I am trying to create a UI for the user to edit their info (for example name or picture). The frontend sends the new information to the backend, and the backend uses the management api to change these root attributes which works as expected. The problem I am having is updating the info on the frontend. I saw a comment that the user object can’t be refreshed, but you can edit it directly with the same changes that were made to the db. This works for me until the page is refreshed, and (I am assuming) the id token gets decoded again and the user object doesn’t contain the changes anymore. Am I doing something fundamentally wrong, or is there a way to refresh the tokens on the frontend so they contain the new information?

The solution may just be to use the Auth.js SDK instead and manage it in storage myself.

Thank you in advance!
Kaden

Hi @nedak96,

Welcome to the Community!

It sounds like the ID token is cached, and is not being refreshed with the proper updates.

The getTokenSilently() method will allow you to request a new token in the background. You can call this method after you get confirmation from your backend that the updates were made successfully. By default, this method will see if there is an existing token that is not expired, and won’t fetch a new one from auth0 if that is the case. You can force it to get a new token with ignoreCache=true

Hope this helps!

Hi Dan. That ignoreCache option was the trick! Sorry I missed that. Made it so reloads had the updated user. Just to be sure, to get the updates before reloading, the user object should be directly modified with the same changes, right?

Awesome. :smile:

You could update it directly like that, but you will still have the old ID token, until you refresh. You could also force getTokenSilently after your API responds with success, updating the token’s claims. It is kind of up to you how you want to handle it.

So right now I have

  useEffect(() => {
    if (updatingUserStatus === 'success') {
      // Update user object for current instance
      Object.keys(newUser).forEach((prop) => { user[prop] = newUser[prop]; });
      // Update tokens in localStorage
      getAccessTokenSilently({
        ignoreCache: true,
      });
      setEdit(false);
    }
  }, [updatingUserStatus, user, newUser, getAccessTokenSilently]);

This works well, and it appears to me that in order to get the updates on reload I need to do the getAccessTokenSilenty call, and to get the updates for the current instance I need to update the user object directly.

1 Like

That makes sense to me.

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.