javascriptfirebasefirebase-authenticationgoogle-cloud-functions

Firebase Cloud Function - null user.displayName onCreate


I'm trying to write a function that will send a welcome email on user creation. I followed along to this tutorial, which says that one can access the newly created user's displayName with user.displayName, though it keeps returning null for me. I realized that the probable reason that this happens (correct me if I'm wrong here) is that registration and setting the user's displayName happens in two separate steps client-side and therefore when onCreate is triggered, user.displayName will naturally be null. Here's my client-side code, for reference:

fb.auth().createUserWithEmailAndPassword(payload.email, payload.password).then(user => {
  return user.user.updateProfile({ displayName: payload.name, });
}).catch(/* ... */);

What I'm looking for is a cloud function that gets triggered on user.updateProfile. I've looked into the auth.user().onOperation function (found here), but when I try to deploy this function to firebase, I get the error Error: Functions did not deploy properly. (helpful, ikr), which I guess has something to do with the onOperation function being private (correct me if I'm wrong).

Is there any way to do what I'm trying to do? If so, how? Alternatively, is there a way to set the displayName on createUserWithEmailAndPassword, so that I can keep using the onCreate function?

Here's my current onCreate code:

exports.sendWelcomeEmail = functions.auth.user().onCreate(user => {
  console.log('name:', user.displayName);
});

And here's my attempt at the onOperation function:

exports.sendWelcomeEmail = functions.auth.user().onOperation(user => {
  console.log('user:', user);
}, 'updateProfile');

Solution

  • If I where you, I wouldnt use firebase auth for user's profile. Maybe is a better idea to use a collection of users, where you have access to update triggers.

    Normally, what I do is to have a trigger when there is new auth user, create a user in the userscollection. With this design you could have a trigger everytime someone updates it's profile.

    exports.onCreateAuthUser = functions.auth.user().onCreate(user => {
      firestore.collection('users').doc(user.uid).set({
         displayName: user.displayName,
         email: user.email,
         // any other properties 
      })
    
      //do other stuff
    });
    
    exports.onUpdateUser = functions
      .firestore.document('users/{id}')
      .onUpdate((change, context) => {
         // do stuff when user's profile gets updated
    }
    

    Hope that helps :)