firebase login sytem in ionic 4
Introduction
I have been working on a personal project of mine in which i am using ionic 4 and firebase. Firebase is a complete solution which has provision for all the web/app development systems like authentication, storage, database etc. We will be looking into how to properly make use of and integrate the firebase authentication module into your ionic 4 app.
login flow
so let’s break down how the authentication is going to work:
- the app root page will be home page
- when app is loading, before loading home page, we will check if user is logged in or not. If not, we will send the user to the login page and authenticate. If user is already logged in, the home page will be shown to the user.
- user will enter email id and password on the login form and submit
- firebase will check username and password and if the user exists, we will redirect the user to the home page.
- user closes app and opens again and the process from step 2 is repeated.
login screens setup
Now, let’s create a basic ionic blank app using ionic cli. If you are not sure about setting up ionic, node and other stuff needed, click here. We will create the blank app using the following command:
ionic start <your app name> blank
now lets create the login page required for the authentication module demo. A login screen to show if the user is not logged in and a home page if the user is logged in:
ionic g page <your pages folder/login>
Once your page is created as shown in the image above, if you run the command ionic serve in you project directory terminal, you will find the output as follows:

you can see that its the default home page as we haven’t made any changes to the app routing yet. But if you change your url from http://localhost:8100/home to http://localhost:8100/login you can also access the login page.

Let’s add the form in our login page so that user can add the emailid and password and submit the form data to firebase for authentication.
First, we will add the card structure inside which we will add input fields, one text and another of type password and a submit button which will have a onLogin method to handle login
Add the following html in login.html file
<ion-header> <ion-toolbar> <ion-title>login</ion-title> </ion-toolbar> </ion-header> <ion-content padding> <ion-card> <ion-card-content> <ion-item> <ion-label position="floating">Email id</ion-label> <ion-input type="email" [(ngModel)]="email" placeholder="enter email-id" ></ion-input> </ion-item> <ion-item> <ion-label position="floating">Floating Label</ion-label> <ion-input type="password" [(ngModel)]="password" placeholder="enter password" ></ion-input> </ion-item> <ion-button (click)="onLogin(email, password)">Login</ion-button> </ion-card-content> </ion-card> </ion-content>
firebase setup
now that we have both the pages ready, we need to install firebase to get started with authentication integration. The integration is simple. just follow the steps given below:
- download firebase module into the project using npm or yarn with command : npm i -S firebase or yarn add firebase
- create a folder named config in your src directory.
- go to your firebase console, create the project and copy the config details. screenshots attached below:



- create a file named firebase.js and add the firebase config inside it as follows:
const firebaseConfig = { apiKey: "AIzaSxxxxxxxxxxxxxxxxxxYlT978Fhg", authDomain: "ionic-xxxxxxxx.firebaseapp.com", databaseURL: "https://ionic-firebase-xxxxxx.firebaseio.com", projectId: "ionic-xxxxxx-dcdae", storageBucket: "ionic-xxxxxx-xxxx.appspot.com", messagingSenderId: "78750xxxxx631" }; export default firebaseConfig;
now that the config is ready in your project , let’s initialise the firebase app in ionic by adding the following on app’s platform.ready method in app.component.ts file:
import firebaseConfig from "../config/firebase"; @Component({...}) export class AppComponent { constructor( privateplatform:Platform, privatesplashScreen:SplashScreen, privatestatusBar:StatusBar ) { this.initializeApp(); } initializeApp() { this.platform.ready().then(() => { firebase.initializeApp(firebaseConfig); ... }); } }
Once this is done, when the app loads, firebase registers the instance and you can use all firebase services in the app now.
setup firebase signin method and add user
Now that our firebase is setup in our ionic app, lets create make use of firebase authentication module to add login functionality for our app. We will start by cretaing a basic form in our login page but before that lets create a dummy user which we can use to log into our app.
Use the following steps to enable the email-password signin method and create a dummy user to test the login functionality.



firebase available methods for login
Our firebase signin method is all set up and our ionic app is integrated with firebase, let’ start using the login methods provided by firebase.
Add the following imports in your login.ts file
import * as firebase from "firebase"; import "firebase/auth";
onLogin(email, password) { firebase .auth() .signInWithEmailAndPassword(email, password) .then(data => { console.log(data); }) .catch(function(error) { // Handle Errors here. varerrorCode=error.code; varerrorMessage=error.message; // ... }); }

As you can see, the login method is working, so the next step is navigating the user to the home page. Let’s add code for that in our on login method.
onLogin(email, password) { firebase .auth() .signInWithEmailAndPassword(email, password) .then(data => { this.navCtrl.navigateRoot('home'); }) ... }
import { Injectable } from '@angular/core'; import { ToastController } from '@ionic/angular'; @Injectable({ providedIn: 'root' }) export class ToastService { constructor(private toastController: ToastController) {} async present(message) { const toast = await this.toastController.create({ message, duration: 2000 }); toast.present(); } }
onLogin(email, password) { ... .catch(error => { // Handle Errors here. const errorCode = error.code; const errorMessage = error.message; this.toast.present(errorMessage); // ... }); }

Let’s Recap…
Till now we have completed the following:
- login form
- on login method logic
- navigate to homepage on successful login
- show toast on unsuccessful attempt
So what remains now?
According to our flow, our root page of the app is homepage so when the app opens it will show homepage instead of login page. Now we will add the last piece of the missing puzzle ie adding a gaurd to our homepage so that ionic app will check if the user is authenticated to access the homepage, if not redirect the user to the login page. Lets get into it then. Add a gaurd with the following command:
ionic g gaurd <your gaurds directory>/auth
in the auth.gaurd file, add the following code. By the way,I got this code from this article here.
import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router'; import * as firebase from 'firebase'; import 'firebase/auth'; @Injectable() export class AuthGuardService implements CanActivate { constructor(public router: Router) {} canActivate(route: ActivatedRouteSnapshot): Promise<boolean> { return new Promise((resolve, reject) => { firebase.auth().onAuthStateChanged(user => { if (user) { // User is signed in. resolve(true); } else { // No user is signed in. resolve(false); this.router.navigate(['login']); } }); }); } }
import { AuthGuardService as AuthGaurd } from './guards/auth.guard'; ... const routes: Routes = [ ... { path: 'home', loadChildren: './pages/home/home.module#HomePageModule', canActivate: [AuthGaurd] } ];
Everything is set except one thing, Let’s add a small Logout button in our pages’ header so that user can end the session. Lets add the logout button on homepage.html file:
<ion-header> <ion-toolbar> <ion-title>home</ion-title> <ion-buttons slot="end"> <ion-button (click)="onLogout()"> logout </ion-button> </ion-buttons> </ion-toolbar> </ion-header> ...
import * as firebase from 'firebase'; import 'firebase/auth'; ... export class HomePage implements OnInit { constructor(private navCtrl: NavController, public toast: ToastService) {} ...onLogout() { firebase .auth() .signOut() .then(() => { // Sign-out successful. this.navCtrl.navigateRoot('login'); }) .catch(error => { this.toast.present(error.message); }); }
Conclusion
Hope this article helps you successfully in setting up the authentication process for your app. If you want you check the source code for the demo app, here . If you have any doubts, suggestions regarding if i missed anything in this topic or topic for my next article, let me know in the comments section below 🙂
You must be logged in to post a comment.