How to send email verification link to your new users

Tools used:
Backend: Firebase -- Version: 7.14.4
Helper Library: @angular/fire -- Version: 6.0.0

Do you know how to prevent people from enter someone else’s email when signing up for your up?

Firebase offers a handy tool for that called email verification link, and it’s a link you send to your users’ emails, they can click it, and it will verify their emails inside of Firebase Authentication.

Then you can decide to only give access to verified users, or run a cleaning tool to remove non-verified users after set period of time.

Prefer the video version?

Let’s get coding

To set up a verification link you first need to decide on when you want to ask for the verification, in this example, you’d want to send the email as soon as the user signs up, that way you can give access only after they verify their emails.

For that you need to go to your signup function, here’s an example of mine, I’ll break down what it’s doing:

async signup(
  email: string,
  password: string
): Promise<firebase.auth.UserCredential> {
  try {
    const newUserCredential: firebase.auth.UserCredential = await this.afAuth.createUserWithEmailAndPassword(
      email,
      password
    );
    await this.firestore
      .doc(`userProfile/${newUserCredential.user.uid}`)
      .set({ email });

    return newUserCredential;
  } catch (error) {
    throw error;
  }
}

First, the function takes an email and password and sends it to the createUserWithEmailAndPassword() function (I think that’s one of the most descriptive function names I’ve seen :-P).

The function returns a UserCredential object, inside of it we can find the user object, where we have the user’s ID, email, etc.

Then it’s creating a new database record for that user, storing the only information we have about them, their email.

For our case, we want to call the send email verification utility right after we create the database record, so our new function would look like this:

async signup(
  email: string,
  password: string
): Promise<firebase.auth.UserCredential> {
  try {
    const newUserCredential: firebase.auth.UserCredential = await this.afAuth.createUserWithEmailAndPassword(
      email,
      password
    );
    await this.firestore
      .doc(`userProfile/${newUserCredential.user.uid}`)
      .set({ email });
    /*
      Here we add the functionality to send the email.
    */
    await newUserCredential.user.sendEmailVerification();

    return newUserCredential;
  } catch (error) {
    throw error;
  }
}

If you take a closer look to the function, we added this line of code:

await newUserCredential.user.sendEmailVerification();

It goes into the newUserCredential object, then into the user object, and then it calls the sendEmailVerification() method.

And that’s it, every new user you create will get an email to verify their accounts, you can then decide on how you’ll handle their access.

Do let me know if you have any questions!