Search code examples
htmlfirebasefirebase-authenticationcustomization

Firebase Authentication using custom fields


I have been using firebase authentication process using email and password. This is working perfectly fine. But i want to add the username while creating the account. But using this auth function i could send only two params like,

const promise = auth.createUserWithEmailAndPassword(name.value, email.value, password.value);

The workaround suggested to me is getting the username after creating the username. But i want the data to sent along with email while creating the account. Is there a way i could send the user name along with this create user request, so that i could get the username whenever i log in. Thanks in advance.


Solution

  • You can only pass an email and a password to createUserWithEmailAndPassword(), so you can't set a name using this function.

    If you want to set a name for the authenticated user, you need to use the updateProfile() method on the user object, like this:

    user.updateProfile({
      displayName: "Jon Snow"
    })
    

    Note that the property is called displayName, not name.

    You can set the name right after creating the user. This example uses async/await:

    const { user } = await auth.createUserWithEmailAndPassword(
      email,
      password
    )
    
    await user.updateProfile({ displayName: name });
    

    Or, using promises:

    auth.createUserWithEmailAndPassword(email, password)
      .then(({ user }) => user.updateProfile({ displayName: name }))
      .then(() => {
        console.log("User was updated!", auth.currentUser.displayName);
      });
    

    If you need the user object somewhere else in your code, you can call firebase.auth().currentUser, or attach a listener to the authentication object.

    You can only set a limited number of properties on Firebase users (like displayName, email and photoURL). Additional (custom) data must be stored somewhere else, e.g. in Firestore, together with the user's uid.