Angular 16 Store User State in Local Storage with Firebase

Last Updated on by in Angular
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 and Firebase (AngularFire2).In this Angular 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.

Setup Angular App

Run the given below command to set up a basic Angular project.

ng new angular-local-storage

Get into the project directory.

cd angular-local-storage

No Property Access From Index Signature

To resolve error:

Property ‘xxxName’ comes from an index signature, so it must be accessed with [‘xxxName’]

This setting makes sure profound consistency between accessing a field via the “dot” (obj.key) syntax, and “indexed” (obj["key"]) and the way which the property is declared in the type.

Without this flag, TypeScript will allow you to use the dot syntax to access fields which are not defined:

Make sure to set noPropertyAccessFromIndexSignature property to false under compilerOptions in tsconfig.json file:

"compilerOptions": {
 ...
 ...
   "strict": false,
   "noPropertyAccessFromIndexSignature": false,
 ...
 ...
}
npm install @angular/fire firebase@9.16.0 --legacy-peer-deps

Next, create environments/ folder and environment.ts file, after that add the following code in the file.

export const environment = {
    production: false,
    firebaseConfig: {
      apiKey: "xxxxxx-xxxxxx_xxxxxxxxxxxxxxxxxx",
      authDomain: "xxxxxx_xxxxxxxxxxxxxxxxxx",
      databaseURL: "xxxxxx_xxxxxxxxxxxxxxxxxx",
      projectId: "xxxxxx_xxxxxxxxxxxxxxxxxx",
      storageBucket: "xxxxxx_xxxxxxxxxxxxxxxxxx",
      messagingSenderId: "xxxxxxxxxxxxxxxxxx",
      appId: "1:xxxxxxxxxxxxxxxxxx:web:xxxxxxxxxxxxxxxxxx"
    }
  };

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

We are going to create an auth service file to create the login authentication service with Angular and Firebase.

In this service file, we’ll write the following methods to show you the demo for local storage in Angular.

  • 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 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 { GoogleAuthProvider } from 'firebase/auth';
import { AngularFireAuth } from '@angular/fire/compat/auth';

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

userState: any;

Angular Storing the User State in Local Storage

To store the user state in Angular 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.signInWithPopup(provider)
    .then((res) => {
      console.log(res)
    }).catch((error) => {
      console.log(error)
  })
}  

GoogleAuth() {
  return this.AuthLogin(new 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.

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

Remove User State from Local Storage

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

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

Final Authentication Service

Open the app.module.ts file, paste the below code line by line in the file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

import { AngularFireModule } from '@angular/fire/compat';
import { environment } from './environments/environment';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule,
    AngularFireModule.initializeApp(environment.firebaseConfig),
  ],
  providers: [],
  bootstrap: [AppComponent],
})

export class AppModule {}

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

import { Injectable } from '@angular/core';
import { GoogleAuthProvider } from 'firebase/auth';
import { AngularFireAuth } from '@angular/fire/compat/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
      .signInWithPopup(provider)
      .then((res) => {
        console.log(res);
      })
      .catch((error) => {
        console.log(error);
      });
  }

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

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

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

Implement Authentication Service in Angular 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/authentication.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})

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

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

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

<!-- // Logout -->
<button (click)="auth.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.

Run the following command to serve your app locally:

ng serve --open

Open a web browser and navigate to:

 http://localhost:4200/

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 and AngularFire2 Local Storage example tutorial.

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

Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.