Ionic 2 Facebook Login: Step-by-step guide to get it working with Firebase

First Published: 6 October 2016
Updated on: 24 September 2018

Ionic 2 Facebook login has become one of the most used methods to get users to sign-in to your hybrid app that it’d be dumb not knowing how to do it.

In this ‘short’ guide, I’m going to walk you through the process of getting someone who just downloaded your app to sign-in using Ionic 2 Facebook login credentials with Firebase.

We’ll break things down into three main steps:

  • Step #1: We’ll create the app and connect it to Firebase.
  • Step #2: We’ll log into your Facebook developer account and set everything up from there.
  • Step #3: We’ll connect Ionic, Firebase, and Facebook to create an authentication process.

Step #1: Create your new Ionic App

1.1) Make sure your development environment is up to date

Before writing any code, we are going to take a few minutes to install everything we need to be able to build this app, that way we won’t have to be switching context between coding and installing.

The first thing we’ll do is install node.js make sure you get the latest LTS version.

The second thing we’ll do is make sure we have Ionic and Cordova installed, we’ll do that by opening your terminal and typing:

npm install -g ionic cordova

Depending on your operating system (mostly if you run on Linux or Mac) you might have to add sudo before the npm install…. command.

1.2) Create the App

Now that you made sure everything is installed and up to date, you’ll create a new Ionic 2 app.

For this, you just need to (while still in your terminal) navigate to the folder you’d like to create it in.

For me, it’s my Development folder in my ~/ directory:

cd Development
ionic start debtTracker blank --v2
cd debtTracker

What those lines there do is the following:

  • First, you’ll navigate to the Development folder.
  • Second, you’ll create the new Ionic 2 app:

  • ionic start creates the app.

  • debtTracker is the name we gave it.

  • blank tells the Ionic CLI you want to start with the blank template.

  • –v2 tells the Ionic CLI you want to create an Ionic 2 project instead of an Ionic 1 project.

  • Third, you’ll navigate into the new debtTracker folder, that’s where all of your app’s code is going to be.

From now on, whenever you are going to type something in the terminal, it’s going to be in this folder unless I say otherwise.

1.3) The npm packages that come with the project

When you use the Ionic CLI to create a new project, it’s going to do a lot of things for you, one of those things is making sure your project has the necessary npm packages/modules it needs.

That means, the start command is going to install ionic-angular all of the angular requirements and more, here’s what the package.json file would look like:

{
  "name": "ionic-hello-world",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "ionic-angular": "3.9.2"
  }
}

Depending on when you read this, these packages might change (specially version numbers) so keep that in mind, also you can leave a comment below if you have any questions/issues/problems with this.

1.4) Install Firebase

Open your terminal (you should already be in the project folder) and install the packages in this order:

npm install firebase --save

1.5) Import and Initialize

Now you can initialize firebase by going to src/app/app.component.js and importing everything you need from Firebase:

You can open your app.module.ts and import everything we’ll be using, and this is the only time you’ll see this file :)

import firebase from 'firebase';

And then add the initialize it inside the constructor:

constructor(platform: Platform) {
    firebase.initializeApp({
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        storageBucket: "",
        messagingSenderId: ""
    });

    platform.ready().then(() => {
    // Okay, so the platform is ready, and our plugins are available.
    // Here you can do any higher level native things you might need.
    StatusBar.styleDefault();
    Splashscreen.hide();
  });
}

In the end the file should look like this:

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { HomePage } from '../pages/home/home';

import firebase from 'firebase';


@Component({
  template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
  rootPage = HomePage;

  constructor(platform: Platform, private statusBar: StatusBar, private splashScreen: SplashScreen) {

    firebase.initializeApp({
      apiKey: "AIzaSyALKfevapBOYK202f6k5mPPfMrT1MHDv5A",
        authDomain: "bill-tracker-e5746.firebaseapp.com",
        databaseURL: "https://bill-tracker-e5746.firebaseio.com",
        storageBucket: "bill-tracker-e5746.appspot.com",
        messagingSenderId: "508248799540"
    });
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}

We are using:

firebase.initializeApp({
  apiKey: '',
  authDomain: '',
  databaseURL: '',
  storageBucket: '',
  messagingSenderId: ''
});

To initialize our Firebase app.

Right there your app should be able to run without any errors when you do ionic serve

You can find your config data (the one that goes inside firebase.initializeApp()) data in the Firebase’s Console.

You just go to the console, click on your app (or create a new one) and there it’s going to give you a few choices.

You’ll pick Add Firebase to your web app because remember we are going to use a mix of AF2 with the JS SDK.

console

If you are running into trouble getting this to work, you can leave a comment below and let me know!

Step #2: Configure your Facebook Developer Console

2.1) Bad News First

Firebase authentication wasn’t entirely compatible with cordova. So the regular JS SDK or AF2 methods to do social sign-in don’t work with Ionic 2 apps yet.

2.2) Now the good news

There’s a workaround, and you need to add some specific operations, especially download a cordova plug-in for Facebook, where you can use their API to get credentials for your user, and then pass those credentials to Firebase.

On the back-end it will be more work, it won’t be as cool as the docs show you, but on the front-end, your user never has to know :)

We need to work a few things with Facebook first to get this working, for example, you need to register as a developer and create an app, you’ll get some data there that you need to pass to the plugin later.

I know it might sound a bit difficult, but let’s just try and see how it goes, OK?

2.3) Create a Facebook App

The first thing you’ll need is to register for a Facebook application. You can go to https://developers.facebook.com/apps and click on the shiny green button that says Create a New App

You’ll be greeted by a pop-up asking you which kind of app you want to create

ionic 2 firebase 3 facebook auth

You can either choose www or tell it to skip and use basic setup, remember, we just need the ID for the plug-in.

After that, you’ll get to name your app and generate an ID.

fb-generate-id

Just fill the info and go, next you can check the data we’re looking for (or if you’re like me you’ll get asked to fill reCAPTCHA because FB thinks you’re a robot).

I created a second app because the first one had spaces in the name and FB still had me go through reCAPTCHA again :(

You’ll get redirected to your app’s dashboard, where you’ll get the information we need.

fb-app-info

2.4) Get the Facebook Plugin

Now we need to get the plugin, detailed instructions are in the ionic-native docs.

But you’re going to open your terminal (by this point you should have your app created and set to work with Firebase and AF2) and type:

ionic plugin add cordova-plugin-facebook4 --variable APP_ID="123456789" --variable APP_NAME="myApplication"

Where APP_ID is the id for the app we just created on the Facebook developers page, and APP_NAME is its name.

Now we need to go back to the Facebook developer page to add both platforms, iOS, and Android, but first, they’re going to ask us for some info, let’s get it now.

Go to your app’s config.xml file and look for this line of code:

<widget id="com.ionicframework.fbauth285351" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">

We’re going to focus on the id property, so take note of that id, for me, is com.ionicframework.fbauth285351 and I’m sure it’s going to be different for you.

Now we need to install the ionic-native package for Facebook:

npm install --save @ionic-native/facebook

And initialize it in app.module.ts so you can use it throughout the app:

import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar'
import { Facebook } from '@ionic-native/facebook'

@NgModule({
  ...,
  providers: [ SplashScreen, StatusBar, Facebook ]
})
export class AppModule {}

2.5) Add the Platforms

Now go back to your app’s dashboard on Facebook and click on settings you’ll see an option that says, add platform.

You’ll get a prompt asking you which platform, just choose iOS and you’ll see this

Facebook Platform Login iOS

Just copy that id into the Bundled ID, then click on “Add Platform” again, this time choose Android and add the ID to the Google play package name.

You’ll get a warning, saying it can’t find the package name, but that’s because the app isn’t up yet, so no biggie.

Facebook Platform Login android

2.6) Enable Firebase

You need to go to your Firebase Console and enable Facebook Authentication, just as you enabled email or anonymous sign-in.

Go to:

console.firebase.google.com/project/YOURPROJECTNAMEHERE/authentication/providers

Enable Facebook; it’s going to ask you for your app’s secret and ID, you can get those from your Facebook app dashboard.

Step #3 Ionic 2 Facebook Login

Now we have all the external configuration done, so it’s time to work on our app, go ahead and open the app in your favorite text editor (after being anti-Microsoft for about six years I’m using VSCode, great TS support :P)

3.1) Create the template

The first thing we’ll do is edit the HomePage template. We want to create a button there, something simple, something that lets our users click and then log-in with Facebook.

After that, we’re going to show them some info on their Facebook profile, and it’s going to look a bit like this.

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h3 center>
    Facebook Auth Example
  </h3>

  <button ion-button center (click)="facebookLogin()">
    Log In with Facebook
  </button>

  <ion-card *ngIf="userProfile">
    <img [src]="userProfile.photoURL" />
    <ion-card-content>
      <ion-card-title>
        {{ userProfile.displayName }}
      </ion-card-title>
      <p>
        The UID for this new user is {{userProfile.uid}} and the email is
        {{userProfile.email}}
      </p>
    </ion-card-content>
  </ion-card>
</ion-content>

Where

<button>
  Log In with Facebook
</button>

Calls the function to log-in with Facebook and

<ion-card *ngIf="userProfile">
  <img [src]="userProfile.photoURL" />
  <ion-card-content>
    <ion-card-title>
      {{ userProfile.displayName }}
    </ion-card-title>
    <p>
      The UID for this new user is {{userProfile.uid}} and the email is
      {{userProfile.email}}
    </p>
  </ion-card-content>
</ion-card>

Facebook Login Button

Is just a card that shows the user’s information, note that we are hiding this card unless the variable userProfile exists, we’ll create that variable in the .ts file.

3.2) Let’s get coding

Now move to home.ts and you should see something like this:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(public navCtrl: NavController) {...}
}

The first thing we’ll do is import Facebook’s plugin and Firebase.

import { Facebook } from '@ionic-native/facebook';
import firebase from 'firebase';

Now create the variable userProfile and inject the Facebook provider into our constructor.

userProfile: any = null;
constructor(public navCtrl: NavController, private facebook: Facebook) {...}

And now we need to do the actual Facebook login. This is going to consist of a few parts.

First, we need to call Facebook’s native plugin to get the user to log-in to Facebook.

Second, we need to get the token from that response and pass it to Firebase to use the signInWithCredential() method.

And third, after we successfully create the Firebase account, we’ll assign the value to userProfile so we can display its data.

facebookLogin(){
    this.facebook.login(['email']).then( (response) => {
        const facebookCredential = firebase.auth.FacebookAuthProvider
            .credential(response.authResponse.accessToken);

        firebase.auth().signInWithCredential(facebookCredential)
        .then((success) => {
            console.log("Firebase success: " + JSON.stringify(success));
            this.userProfile = success;
        })
        .catch((error) => {
            console.log("Firebase failure: " + JSON.stringify(error));
        });

    }).catch((error) => { console.log(error) });
}

By the end, your file should look something like this

import { Component } from '@angular/core';
import { Facebook } from '@ionic-native/facebook';
import { NavController } from 'ionic-angular';

import firebase from 'firebase';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  userProfile: any = null;
  constructor(public navCtrl: NavController, private facebook: Facebook) {}

  facebookLogin(): void {
    this.facebook.login(['email']).then( (response) => {
      const facebookCredential = firebase.auth.FacebookAuthProvider
        .credential(response.authResponse.accessToken);

      firebase.auth().signInWithCredential(facebookCredential)
        .then((success) => {
          console.log("Firebase success: " + JSON.stringify(success));
          this.userProfile = success;
        })
        .catch((error) => {
          console.log("Firebase failure: " + JSON.stringify(error));
      });

    }).catch((error) => { console.log(error) });
  }
}

And after success, you should see all the information inside the app

Facebook Login Screen

By now you have a fully working sign-in process with Facebook using Firebase, now, It might not be ideal, but it’s what we can do now.

You just went through a lot:

First, you set-up your development environment and made sure everything was up-to-date.

Then you created a Facebook developer account and created an app there

And then you connected everything in your Ionic app to allow users to sign-up using their Facebook accounts :)

Next Steps

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.