Firebase auth sendEmailVerification not sending email // react

Viewed 53

I have a sign up form for my react app using firebase auth.

The sign up function works great, it is just not sending a verification email. This is the code I am using:

  const registerUser = async (email, name, password) => {
    try {
      console.log("> Registering user")
      setLoading(true);
      const {
        user
      } = await createUserWithEmailAndPassword(auth, email, password)
  
      console.log("> Updating profile")
      await updateProfile(user, {
        displayName: name,
      })
      .then(()=>{
        // send verification mail.
        sendEmailVerification(auth.currentUser.email);
      auth.signOut();
      alert("Email sent");
    })
    .catch(alert); 
  
     window.location.pathname = `/subscriptions/${user.uid}`;
    } catch (e) {
      console.log(e)
    }
  
    setLoading(false)
  };

The alert("Email sent") works fine, and it has sent a verification email in the past. I changed it since then however and can't remember what I used to make it send the verification email.

1 Answers

Avoid mixing traditional .then().catch() syntax with modern async/await syntax as it can lead to confusion.

In your code, you call both sendEmailVerification() and auth.signOut() without waiting for them to complete. This means that alert("Email sent") is called straight away, followed by window.location.pathname = `/subscriptions/${user.uid}` , which cancels those two operations.

const registerUser = async (email, name, password) => {
  try {
    console.log("> Registering user")
    setLoading(true);
    const { user } = await createUserWithEmailAndPassword(auth, email, password)
  
    console.log("> Updating profile")
    await updateProfile(user, { displayName: name });

    await sendEmailVerification(user.email);

    await auth.signOut();

    alert("Email sent"); // avoid using alert() as it blocks the thread
  
    window.location.pathname = `/subscriptions/${user.uid}`;
  } catch (e) {
    // consider swapping below line to `setErrorMessage()` or similar
    // and display the message above your form
    alert('Failed to send email verification: ' + (e.message || e)); 
    console.error('Failed to send email verification: ', e);
  }
  
  setLoading(false)
};

If you want to use custom error messages after each step, see this answer here to see how to use catch() to wrap the errors (however only use new Error() as new functions.https.HttpsError() is for server-side code).

Related