How do I prevent a new user from login until they verify their email address?

First Published: 18 January 2018
Updated on: 24 September 2018

Hello, please have you done any tutorials on email verification using firebase for ionic? I found out in the docs how to firebase.auth().currentUser.sendEmailVerification(), but what I can’t figure out if how to prevent the app from login in the new user until they have verified their accounts in the email sent to them.

I get that question a lot, so first let me start by saying I’m sorry it took me this long to write it down.

We usually have an authentication observer to redirect the user based on logged in status, and it’s something like this:

const unsubscribe: Unsubscribe = firebase
  .auth()
  .onAuthStateChanged(user => {
    if (!user) {
      this.rootPage = 'LoginPage';
      unsubscribe();
    } else {
      this.rootPage = HomePage;
      unsubscribe();
    }
  });

You can add the email verification there, something like this will work for you:

const unsubscribe: Unsubscribe = firebase
  .auth()
  .onAuthStateChanged(user => {
    if (user && user.emailVerified()) {
      this.rootPage = HomePage;
      unsubscribe();
    } else {
      this.rootPage = 'LoginPage';
      unsubscribe();
    }
  });

The user.emailVerified() returns a boolean, so if both conditions meet the user can go to the home page, if they don’t then the user is sent to the login page.

You can add more logic to it to display a message to the user letting them know when they can’t log in because of an unverified email address. ‚Äč

For example, you can break down the first conditional to ask:

const unsubscribe: Unsubscribe = firebase
  .auth()
  .onAuthStateChanged(user => {
    if (user) {
      if(!user.emailVerified()){
        // Here you can create an alert to let the user know that
        // the reason they can't log in is that they haven't verified
        // their email address.
      } else {
        this.rootPage = HomePage;
        unsubscribe();
      }
    } else {
      this.rootPage = 'LoginPage';
      unsubscribe();
    }
  });

You can also query the database inside of the onAuthStateChanged() so if you have any logic on the database that determines where the user gets redirected, that’s the place it should go.

If you have any questions don’t forget you can always leave a comment below.

If you want to take a deeper dive on Ionic + Firestore you should go through my FREE course: Build your first Firestore powered Ionic app.