Angular 8 Store User State in Local Storage with Firebase 6

By Digamber Rawat Last updated on
Today we are going to discuss the most talked about topic in the web development industry, and that is how to store user state in local storage using Angular 8 and Firebase (AngularFire2). In this Angular 8 local storage tutorial, you are about to learn how to store user state in the web browser’s local storage memory. After successfully reading this tutorial, you will be able to manage the user data in local storage.

To understand this topic thoroughly, we will need the following frameworks, npm packages, and database set up in our system. However, if you are an absolute beginner, then I would suggest you should go through by the following tutorials.

What is Local Storage?

Local storage is an HTML5 mechanism to store the data in the web browser, and it allows the user to manage and store the data in the browser. It works even when there is no internet connection available. You can still see your data even if you refresh the web page.

Create Auth Service in Angular 8

We are going to create an auth service file to create the login authentication service with Angular 8 and Firebase. In this service file, we’ll write the following methods to show you the demo for local storage in Angular 8.

  • Login with Google
  • Sign-in with email/password
  • Storing user state in local storage when a user logged in
  • Removing user state from local storage when a user logged out

Generate Angular Authentication Service File

Enter the below command to create the authentication service in Angular 8 project.

ng g s shared/authentication

Importing AngularFire2 Authentication Service Libraries

Once the authentication.service.ts file is created, then you should get into the authentication file in shared folder and import the following AngularFire 2 services.

import { Injectable } from '@angular/core';
import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";

Now declare a variable in AuthenticationService class, this variable will hold the user state.

userState: any;

Storing the User State in Angular 8 Local Storage

To store the user state in Angular 8 local storage mechanism, inject the AngularFireAuth service in the constructor class. As you can see in the below example if the user is signed in then, we are storing the user data as a JSON object in the local storage and removing the user data when the user is logged out.

constructor(
    public afAuth: AngularFireAuth
  ) {    
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userState = user;
        localStorage.setItem('user', JSON.stringify(this.userState));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

Create Sign-in with Google

Let’s create Auth provider function, this function will help us to log-in with google auth service.

// Auth provider
AuthLogin(provider) {
  return this.afAuth.auth.signInWithPopup(provider)
    .then((res) => {
      console.log(res)
    }).catch((error) => {
      console.log(error)
  })
}  

// Sign-in with Google
GoogleAuth() {
  return this.AuthLogin(new auth.GoogleAuthProvider());
}

AngularFire2 Sign-in with email/password

Add the following code in authentication.service.ts file, to create sign-in with Google using Firebase auth and Angular 8.

// Sign-in with email/password
SignIn(email, password) {
   return this.afAuth.auth.signInWithEmailAndPassword(email, password)
     .then((res) => {
       console.log(res)
   }).catch((error) => {
       console.log(error)
   })
}

Remove User State from Local Storage in Angular 8

In the following example you can check out how to remove user state from local storage when the user logged out from the Angular 8 application.

SignOut() {
 return this.afAuth.auth.signOut().then(() => {
   localStorage.removeItem('user');
 })
}

Final Authentication Service

This is the final authentication.service.ts file for our Angular 8 local storage tutorial.

import { Injectable } from '@angular/core';
import { auth } from 'firebase/app';
import { AngularFireAuth } from "@angular/fire/auth";

@Injectable({
  providedIn: 'root'
})

export class AuthenticationService {
  userState: any;

  constructor(
    public afAuth: AngularFireAuth
  ) {    
    this.afAuth.authState.subscribe(user => {
      if (user) {
        this.userState = user;
        localStorage.setItem('user', JSON.stringify(this.userState));
        JSON.parse(localStorage.getItem('user'));
      } else {
        localStorage.setItem('user', null);
        JSON.parse(localStorage.getItem('user'));
      }
    })
  }

  // Auth provider
  AuthLogin(provider) {
    return this.afAuth.auth.signInWithPopup(provider)
    .then((res) => {
      console.log(res)
    }).catch((error) => {
      console.log(error)
    })
  }  

  // Login with Google
  GoogleAuth() {
    return this.AuthLogin(new auth.GoogleAuthProvider());
  }  

  // Signin with email/password
  SignIn(email, password) {
    return this.afAuth.auth.signInWithEmailAndPassword(email, password)
      .then((res) => {
        console.log(res)
      }).catch((error) => {
        console.log(error)
      })
  }

  // Sign out 
  SignOut() {
    return this.afAuth.auth.signOut().then(() => {
      localStorage.removeItem('user');
    })
  }

}

In this step, import AuthenticationService in app.module.ts file.

import { AuthenticationService } from "./shared/services/authentication.service";

@NgModule({
  providers: [AuthService]
})

Implement Authentication Service in Angular 8 Template

Now we are going to implement auth service in app HTML template. Go to app.component.ts file and include the following code.

import { Component } from '@angular/core';
import { AuthenticationService } from "../../shared/services/authentication.service";

@Component({
  [...]
})

export class AppComponent {
  constructor(
    public auth: AuthenticationService
  ) { }
}

Go to app.component.html file and include the following code.

// Sign-in with Google
<button 
   (click)="authenticationService.GoogleAuth()">
   Sign-in with Google
</button>

// Logout
<button 
   (click)="authenticationService.SignOut()">
   Sign-out
</button>

Now we are all set to store the user data in the local storage, click on the sign-in with google button and check your browser’s console.

local storage data

In the same way if you click on the sign-out button, user data will be removed from the local storage.

Finally, we are done with Angular 8 & AngularFire2 Local Storage tutorial. If you would like to try your hand on Firebase authentication service, then check out this tutorial: Firebase Authentication in Angular 8 with AngularFire2.

Don’t forget to share this tutorial with others as well.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.