Search code examples
node.jsfirebasefirebase-authenticationfirebase-admin

Get User Display Name from Firebase VerifyToken (part2)


I have the same situation as the other post with the same title. I have a custom backend (node+express) and I am able to update the displayName on the front end. However, when looking at the DecodedIdToken on the backend, there's no "name" when registering the user. I need the display name of the user so it can be synced with other clients on the backend.

If I sign out the newly registered user and log back in, the DecodedIdToken now shows the "name" on the backend.

Client side code:

firebase
  .auth()
  .createUserWithEmailAndPassword(email, password)
  .then(dataBeforeEmail => {
    firebase.auth().onAuthStateChanged(function(user) {
      user.sendEmailVerification();
      user.updateProfile({displayName: displayName})
    });
  })
 .then(dataAfterEmail => {
    firebase.auth().onAuthStateChanged(async function(user) {
      if (user) {
        // Sign up successful
        dispatch({
          type: REGISTER_SUCCESS,
          payload:user
        });

        const header = await tokenConfig();
       
        try{
          axios
          .post('/api/auth/',{}, header)
          .then(res=>
            dispatch({
              type: REGISTER_SUCCESS,
              payload: res.data
            })
            (console.log(res.data))
            )
        }
        catch(err) {
          dispatch({
            type: REGISTER_FAIL,
            payload:
                "Something went wrong, we couldn't create your account. Please try again."
            });
          };

export const tokenConfig = async () => {
  const user = firebase.auth().currentUser;
  const token = user && (await user.getIdToken());
 const config = {
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${token}`,
    },
  };
  return config;
};

Is there a way to have it show without having the user log out and log back in?


Solution

  • This is because of how the client SDK is handling the ID tokens. ID tokens are cached up to an hour. So you have to do one of the following before any changes to the user account are reflected on the ID token:

    1. Wait for the current ID token to expire, and the SDK to automatically fetch a new one.
    2. Sign-out and sign-in, which cycles out the ID token.
    3. Explicitly request an ID token refresh on the client SDK. If you're using the JS SDK this will look something like this:
    firebase.auth().currentUser.getIdToken(/* forceRefresh */ true)
    

    For more details: