How to use Firebase in your Ionic 4 app — Guide for beginners

Abhijeet Rathore
Mar 8 · 11 min read
  1. It’s R-E-A-L T-I-M-E 🕺.
    If you are a developer, you understand the importance of a real-time back-end/database in today’s app market. Things like chat, news feeds, ratings, bookings etc all are very easy if you factor in real-time operations
  2. Simple Authentication operations.
    The very first things required in a user facing application is login/register operations. Firebase handles this very smoothly and with minimum coding effort. You can integrate a number of social authentication services like Facebook, Google etc. with Firebase as well.
  3. You get tonnes of additional features in-built e.g. push notifications, analytics etc 😍😍
  4. It’s free, up to a certain usage limit. But this is pretty awesome for developers who are trying things, or making MVPs, or even for small scale app businesses. 🤑

1. Analytics Firebase

ionic cordova plugin add cordova-plugin-firebase-analyticsnpm install @ionic-native/firebase-analytics
import { FirebaseAnalytics } from '@ionic-native/firebase-analytics/ngx';
constructor(private firebaseAnalytics: FirebaseAnalytics) {
... your code here
}
this.firebaseAnalytics.logEvent('my_event', {param1: "value1"})
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));
This is how Firebase automatically projects the analytics for your app
  1. Set User Propertythis.firebaseAnalytics.setUserProperty("name","value")
    This is useful to create filters with respect to users doing a certain action or behaving a certain way to an event in the app. These filters come in handy when you want to send push notification or in-app messages to selected channels.
  2. Set Current Screen this.firebaseAnalytics.setUserId("123123")
    This option comes in handy to identify events with respect to screens. For example — which screen do users usually quit the app on etc.
Firebase Dashboard for Events Analytics

2. Firebase Cloud Messaging (FCM)

ionic cordova plugin add cordova-plugin-firebase-analyticsnpm install @ionic-native/firebase-analytics
import { FCM } from '@ionic-native/fcm/ngx';constructor(private fcm: FCM) {}

I. Receiving Token Refresh

this.fcm.onTokenRefresh().subscribe(token => {
alert(token);
});

II. Get token

this.fcm.getToken().then(token => {
alert(token);
});

III. Subscribe to topic

this.fcm.subscribeToTopic('marketing');

IV. Unsubscribe from topic

this.fcm.unsubscribeFromTopic('marketing');

V. Receiving push notification data

this.fcm.onNotification().subscribe(data => {
if(data.wasTapped){
console.log("Push received in background");
} else {
console.log("Push received in foreground");
};
});
Prepare a Push notification right from Firebase console
{
"notification":{
"title":"Notification title",
"body":"Notification body",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"data":{
"param1":"value1",
"param2":"value2"
},
"to":"/topics/topicExample",
"priority":"high",
"restricted_package_name":""
}

3. Firebase (Remote) Config

ionic cordova plugin add cordova-plugin-firebase-confignpm install @ionic-native/firebase-config
import { FirebaseConfig } from '@ionic-native/firebase-config/ngx';constructor(private firebaseConfig: FirebaseConfig) { }
this.firebaseConfig.getBoolean('is_my_holiday_promotion_on')
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));
Define Remote config parameters in Firebase console
Setting custom conditions for Firebase Remote Config

4. Firebase dynamic links

Add Dynamic Links from Firebase Console
  • Increase conversion for user-to-user sharing. e.g. app invites , coupons etc.
  • Drive more installs with social, email, and SMS marketing campaigns.
  • Turn desktop users into mobile app users. Send users to app store
  • User specific conversion — If a user installed your Food app from an ad that mentioned Chinese Food, then after installation, you can take the user directly to a Chinese restaurant page. Cool, right ?
ionic cordova plugin add cordova-plugin-firebase-dynamiclinksnpm install @ionic-native/firebase-dynamic-links
import { FirebaseDynamicLinks } from '@ionic-native/firebase-dynamic-links/ngx';
constructor(private firebaseDynamicLinks: FirebaseDynamicLinks) { }
this.firebaseDynamicLinks.onDynamicLink()
.subscribe((res: any) => console.log(res), (error:any) => console.log(error));

5. Firebase Authentication

Use our Firebase Starter Kit to get started with Firebase Authentication.

Firebase provides various methods to authenticate users
ionic cordova plugin add cordova-plugin-firebase-authenticationnpm install @ionic-native/firebase-authentication
import { FirebaseAuthentication } from '@ionic-native/firebase-authentication/ngx';constructor(private firebaseAuthentication: FirebaseAuthentication) { }

I. Register a User with Email and Password

this.firebaseAuthentication.createUserWithEmailAndPassword('test@gmail.com', '123')
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

II. Send Email Verification

Initiates email verification for the current user.

this.firebaseAuthentication.sendEmailVerification()
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

III. Send Password Reset Email

Triggers the Firebase Authentication backend to send a password-reset email to the given email address, which must correspond to an existing user of your app.

this.firebaseAuthentication.sendPasswordResetEmail()
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

IV. Login with Email & Password

Asynchronously signs in using an email and password.

this.firebaseAuthentication.signInWithEmailAndPassword('test@gmail.com', '123')
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

V. verifyPhoneNumber(phoneNumber, timeout)

Starts the phone number verification process for the given phone number.

this.firebaseAuthentication.verifyPhoneNumber('+123456789', '30000')
.then((res: any) => console.log(res))
.catch((error: any) => console.error(error));

VI. Sign-in anonymously

Create and use temporary anonymous account to authenticate with Firebase.

this.firebaseAuthentication.signInAnonymously().then(function(userInfo) {
// user is signed in
});

VII. Google login — signInWithGoogle(idToken, accessToken)

Uses Google’s idToken and accessToken to sign-in into firebase account. In order to retrieve those tokens follow instructions for Android and iOS.

VIII. Facebook login — signInWithFacebook(accessToken)

Uses Facebook’s accessToken to sign-in into firebase account. In order to retrieve those tokens follow instructions for Android and iOS.

IX. Twitter login — signInWithTwitter(token, secret)

Uses Twitter’s token and secret to sign-in into firebase account. In order to retrieve those tokens follow instructions for Android and iOS.

X. Sign out

Signs out the current user and clears it from the disk cache.

this.firebaseAuthentication.signOut().then(function() {
// user was signed out
});

Conclusion:

In this blog we learnt about a lot of features provided by Firebase for Ionic apps. You can create user auth modules to analytics, dynamic link for invites, push notifications, remote config and much more. Firebase is truly a great match for modern day mobile apps and is really developer friendly.



Enappd

App starters, Themes, Templates, Complete Web and Mobile Apps Solutions

Abhijeet Rathore

Written by

Rocket scientist turned programmer. Co-founder at Enappd and Youstart Education. Trying to make the world a better place, one solution at a time.

Enappd

Enappd

App starters, Themes, Templates, Complete Web and Mobile Apps Solutions