How to verify your users email address with Firebase Auth

Jorge Vergara pointing at a target showing an arrow in the bullseye

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’ email, they can click it, and it will verify their email 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.

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:

import { Component } from '@angular/core';
import {
  Auth,
  UserCredential,
  createUserWithEmailAndPassword,
} from '@angular/fire/auth';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  constructor(private readonly auth: Auth) {}

  async signup(email: string, password: string): Promise<UserCredential> {
    return createUserWithEmailAndPassword(
      this.auth,
      email,
      password
    );
  }
}

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.

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

import { Component } from '@angular/core';
import {
  Auth,
  UserCredential,
  createUserWithEmailAndPassword,
  sendEmailVerification
} from '@angular/fire/auth';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  constructor(private readonly auth: Auth) {}

  async signup(email: string, password: string): Promise<UserCredential> {
    const userCredential = await createUserWithEmailAndPassword(
      this.auth,
      email,
      password
    );
    await sendEmailVerification(userCredential.user);
    return userCredential;
  }
}

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

await sendEmailVerification(userCredential.user);

It uses the sendEmailVerification() function and sends the user as a parameter. You can import that function from @angular/fire/auth

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!