Js Mobile Dev About Courses Articles Youtube Services Contact

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

Libraries and Versions

Backend: Firebase v7.7.0
Frontend: @ionic/angular v5.0.0

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.router.navigateByUrl('loign');
    unsubscribe();
  } else {
    this.router.navigateByUrl('home');
    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.router.navigateByUrl('home');
    unsubscribe();
  } else {
    this.router.navigateByUrl('login');
    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.router.navigateByUrl('home');
      unsubscribe();
    }
  } else {
    this.router.navigateByUrl('login');
    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.


Become a Mobile Developer using JavaScript

Leave your email below and you'll get one or two emails a month sharing articles, videos, or courses that will help you jump-start your development with Ionic, Firebase, and Angular 🚀.

    I don't do the spam thing, you can one-click unsubscribe at any time