0

I am trying to read the user's custom claims and I would like to return the values of the claims to the client individually.

This code has worked for months. However, all of a sudden it returns the error "Object is possibly undefined".

This code appears on the following lines:

role: userRecord.customClaims["role"],
type: userRecord.customClaims["type"],

Here is the entire code snippet:

exports.checkAuthClaim = functions.https.onCall(async (data, context) => {
  const userId = data.userId;
  return admin
      .auth()
      .getUser(userId)
      .then((userRecord) => {
        console.log(userRecord.customClaims);
        return {
          role: userRecord.customClaims["role"],
          type: userRecord.customClaims["type"],
        };
      });
});

Any help is appreciated :)

devOP1
  • 295
  • 3
  • 13
  • Hi @devOP1 , just want to confirm, if this question is related to your another [question](https://stackoverflow.com/questions/72794009/get-data-from-firestore-document-and-use-in-cloud-function). It seems that you have the same error but you haven't found yet what's causing the issue. – Marc Anthony B Jun 29 '22 at 06:30

1 Answers1

1

the user maybe undefined, this could happen if you use invalid userId. Use optional chaining to get rid of this error.

        return {
          role: userRecord?.customClaims?.["role"],
          type: userRecord?.customClaims?.["type"],
        };

simply check for the undefined

devOP1
  • 295
  • 3
  • 13
Acid Coder
  • 2,047
  • 15
  • 21