Get User Display Name from Firebase VerifyToken

Viewed 1097

I have a custom back-end to which the client send the login firebase token which the server verifies and gets the decoded token, for the most part it contains enough information but I need the display name of the user with it to sync it with other clients, I can however make this by calling admin.auth().getuser(uid) I want to avoid making extra call and have other round trip just to get the display name.
Maybe I am overthinking but Isn't there a way to get that in a single call with verifyToken?

3 Answers

DecodedIdToken has many optional properties that are not explicitly listed. You can access them by treating the DecodedIdToken as a map. Following works as expected for me:

const admin = require('firebase-admin');

admin.initializeApp({
  projectId: '...',
})

const token = '....';
admin.auth().verifyIdToken(token)
  .then((decodedIdToken) => {
    console.log(decodedIdToken.name); // Get user's display name
    // decodedIdToken['name'] if you're on TypeScript
  });

The name property is only present when the user has signed in using a provider that exposes that information (such as google auth).

As you can see from the API documentation, verifyIdToken() returns a DecodedIdToken object. As far as I can see, it has no field for display name - it's not part of the payload of the ID token. getUser(), however returns a UserRecord object, and that has a displayName property.

Since it's an optional field, you should check first if it's undefined, and figure out what you want to display in that case.

I think the best way would be to get user profile on client side and send the display name along with Firebase Token. as @Doug has highlighted there is no field for display name and my aim with this question was to avoid extra bandwidth billing on the server side this approach does exactly that.
Again, I could be over thinking but somehow I am obsessed with everything being perfect!

Related