Learn how Firebase Anonymous Login works on Ionic Framework apps

First Published: 24 August 2016
Updated on: 9 June 2019

Have you worked with Firebase Anonymous Login before? The idea is perfect, let’s say you want to create an app, and have users be able to use it, and be able to save some stuff to your database without signing in and if they want to use more features, they’ll need to create an account.

Now Firebase Anonymous Login lets us do that, and also it enables you to link the anonymous account with the new email + password account, so the user’s data is always there.

So now I’m going to stop talking and jump straight to the code!

Firebase Anonymous User Creation

To create the user you need to call the .signInAnonymously() function:

createAnonymousUser(): Promise<any> {
  return this.fireAuth.signInAnonymously();
}

Once you do that, it creates a user on your Firebase app, with no auth provider or information, all it has is a user’s ID.

Let’s say you have an app where every authenticated user can see a list of events, and when they click the event they go into the details of the event, like the location where it will be.

You want to keep that information secure and only give it to full users, you don’t want someone anonymous to have access to that!

You can have a route guard protecting the detail page that verifies if the user is anonymous or not.

You can do that by getting the current user and access the .isAnonymous property:

firebase.auth().onAuthStateChanged(user => {
  if (user.isAnonymous === true) {
    // Redirect to a page for the user to give you their credentials.
  } else {
    // Give access to the detail page.
  }
});

You can have anonymous users give you their credentials, to give you an email and password to ‘upgrade’ to a full account, once they give you the credentials you can use the link property:

linkAccount(email: string, password: string): Promise<any> {
  const credential = firebase.auth.EmailAuthProvider.credential(
    email,
    password
  );

  return firebase.auth().currentUser.linkWithCredential(credential).then(
    userCredential => {
      this.firestore
        .doc(`/userProfile/${userCredential.user.uid}`)
        .update({ email });
    },
    error => {
      console.log('There was an error linking the account', error);
    }
  );
}

And that’s it, that’s how you take an anonymous account and turn it into a full account.

Do you see any use cases for this? I’m releasing an app for a client in ~~ two weeks~~ we’re live now! And we used it so people could use one major feature from the app without needing to create accounts, it works very well for us there.

Let me know how you’ll use this in the comments below!