Firebase custom claims returns Object is possibly 'undefined'

154 views Asked by At

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 :)

2

There are 2 answers

2
Acid Coder On BEST ANSWER

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

0
Rishabh Agrawal On

It means your claims must be null in that case.

you need to explicitly set the claim then you can access it

  initializeApp({ projectId: 'enter-project-id' })
  const uid = 'user-id';
  auth.getAuth()
    .getUser(uid)
    .then((userRecord) => {
      auth.getAuth().setCustomUserClaims(uid,{...userRecord.customClaims, superadmin: true}).then(() => {
        console.log('[setCustomUserClaims] set successfully')
      })
      .catch((error) => {
        console.log('Error creating custom token:', error);
      });
    }).catch((error) => {
      console.log('Error getting user:', error);
    });