DEV Community

Amalia Hajarani
Amalia Hajarani

Posted on

How to: Integrating Firebase Cloud Messaging - Angular - ExpressJs (2: Create and Integrate Angular with Firebase)

Prerequisites

Installed Node version of: v20.10.0.

Installing Angular Cli

You can see the official documentation for a better explanation.

  1. Open command prompt and run command below:

    npm install -g @angular/cli
    

Create new Angular project

  1. Open a command prompt from a dedicated directory to store your Angular project.
  2. Run this command:

    ng new angular-with-firebase // you can change angular-with-firebase with anything else
    
  3. You will be asked to configuring few things. For stysheet format, I choose CSS. Then hit enter.
    Image description

  4. I don't know much about this so I choose no by typing N, then hit enter.
    Image description

  5. Your project now is being created.

  6. Once it done, open command prompt from inside your project and run ng serve to see our new project. By default, we will have it run at http://localhost:4200/.
    Image description
    Image description

Connecting Firebase with Angular

Configuring Firebase environment

  1. Open your project dashboard on Firebase Console.
  2. Click at settings icon near the Project Overview that you can find at upper left corner. Image description
  3. Choose Project settings. Image description
  4. Scroll down to your apps section. You will see a code snippet, the same one as when we first create the project. I choose npm because I will be using npm. Image description
  5. Back to our Angular project directory, open command prompt. Let's install Firebase by running:

    npm install firebase
    
  6. Once Firebase package installed, open our project in a code editor. I'm using Visual Studio Code.

  7. In src directory, create new directory called environments. Inside this new directory, create a new file called environment.ts. This is what is going to be inside that file:

    export const environment = {
      production: false,
      firebaseConfig: {
    
        // to cut the chase, just copy it the snippet on step 3
        apiKey: "abcdefghijklmnopqrstuvwxyz",
        authDomain: "domain-firebase.firebaseapp.com",
        projectId: "project-id",
        storageBucket: "storage-bucket",
        messagingSenderId: "1234567890",
        appId: "acnqw3nry23ibcadmqomxue38e23e28x29m",
        measurementId: "G-6GG2Q2LX8S",
    
        // You are not yet have this
        vapidKey: ""
      }
    }
    
  8. To have your vapidKey, go back to your Firebase Project settings.

  9. Go to Cloud Messaging tab.
    Image description

  10. Scroll until you see Web configuration section. Click Generate key pair button.
    Image description

  11. Copy the value under Key pair section.
    Image description

  12. Let's get back to step 7. Paste your key to vapidKey field.

    export const environment = {
      production: false,
      firebaseConfig: {
        apiKey: "abcdefghijklmnopqrstuvwxyz",
        authDomain: "domain-firebase.firebaseapp.com",
        projectId: "project-id",
        storageBucket: "storage-bucket",
        messagingSenderId: "1234567890",
        appId: "acnqw3nry23ibcadmqomxue38e23e28x29m",
        measurementId: "G-6GG2Q2LX8S",
        vapidKey: "BIddLYYlBZA1mijjbsG5ixKrvNgCqmy2H-qgI-PXSn84danwe7dtJOXjs9IDhNo_nQK0QzRKA96ocW8SDbKk5nRU"
      }
    }
    
  13. Now, back to src directory, create new directory called configs. Inside that directory, create a new file called firebase.config.ts. This is the content of the newly created file:

    import firebase from 'firebase/compat/app';
    import { environment } from "../environments/environment";
    import 'firebase/compat/messaging';
    
    firebase.initializeApp(environment.firebaseConfig);
    export const messaging = firebase.messaging();
    

Working with service workers

  1. To work with service worker we going to need new dependency, so open a command prompt from your project directory and run:

    npm install @angular/service-worker
    
  2. Go to Firebase Project Settings.

  3. Go to Firebase Cloud Messaging API (V1), there you will see a table containing your Sender ID. Copy the Sender ID.
    Image description

  4. Back to our code editor, in src directory, create a file called manifest.json. Paste your Sender ID here.

    {
      "gcm_sender_id": "YOUR_SENDER_ID"
    }
    
  5. Open index.html at the same directory, in head tag, add:

    <link rel="manifest" href="./manifest.json">
    

    Image description

  6. Still in src directory, create a file called firebase-messaging-sw.js.

    importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-app-compat.js");
    importScripts("https://www.gstatic.com/firebasejs/9.1.3/firebase-messaging-compat.js");
    
    const firebaseConfig = {
      // to cut the chase, just copy it from your Firebase Project settings
    
        apiKey: "abcdefghijklmnopqrstuvwxyz",
        authDomain: "domain-firebase.firebaseapp.com",
        projectId: "project-id",
        storageBucket: "storage-bucket",
        messagingSenderId: "1234567890",
        appId: "acnqw3nry23ibcadmqomxue38e23e28x29m",
        measurementId: "G-6GG2Q2LX8S",
    };
    
    const app = firebase.initializeApp(firebaseConfig);
    const messaging = firebase.messaging();
    
  7. Go to project root directory, and find angular.json. Add this line in assets:

    "src/manifest.json",
     "src/firebase-messaging-sw.js"
    

    Image description

  8. Back to command prompt, run:

    ng build
    

Creating new Angular Component

  1. Open command prompt from your Angular project directory. Run this command:

    ng generate component notification --inline-template
    
  2. Once it's done, you will see new directory inside src/app called notification.
    Image description

  3. Now, with your code editor, open notification.component.ts.

  4. Now, let's cook something from here. To check if we already correctly configure anything, I add some simple function. Now, my notification.component.ts looks like:

    import { Component, OnInit } from '@angular/core';
    import { messaging } from '../../configs/firebase.config';
    import { environment } from '../../environments/environment';
    
    @Component({
      selector: 'app-notification',
      standalone: true,
      imports: [],
      template: `
        <p>
          notification works!
        </p>
      `,
      styleUrl: './notification.component.css'
    })
    export class NotificationComponent implements OnInit {
    
      ngOnInit(): void {
        this.requestPermission();
        this.listen();
      }
    
      requestPermission() {
        messaging.getToken({vapidKey: environment.firebaseConfig.vapidKey})
          .then((currentToken) => {
            if (currentToken) {
              console.log(currentToken);
            } else {
              console.log('No registration token available. Request permission to generate one.');
            }
          }).catch((err) => {
            console.log(err);
          });
      }
    
      listen() {
        messaging.onMessage((incomingMessage) => {
          console.log(incomingMessage);
        })
      }
    
    }
    
  5. Now, open app.component.ts which you can find at src\app\app.config.ts. Add NotificationComponent at imports section.

    import { Component } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { RouterOutlet } from '@angular/router';
    import { NotificationComponent } from './notification/notification.component';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [CommonModule, RouterOutlet, NotificationComponent],
      templateUrl: './app.component.html',
      styleUrl: './app.component.css'
    })
    export class AppComponent {
      title = 'angular-with-firebase';
    }
    
  6. Open app.component.html at src\app\app.component.html. At the end of last div close tag, add <app-notification></app-notification>
    Image description

  7. Create a new file called app.module.ts at the same level directory as app.component.ts and app.component.html (here's the relative path: src\app\app.module.ts). Here's how I defined it:

    import { NgModule } from "@angular/core";
    import { BrowserModule } from "@angular/platform-browser";
    import { NotificationComponent } from "./notification/notification.component";
    import { messaging } from "../configs/firebase.config";
    
    @NgModule({
      declarations: [],
      imports: [
        BrowserModule,
        NotificationComponent
      ],
      providers: [
        { provide: 'messaging', useValue: messaging}
      ],
      bootstrap: []
    })
    export class AppModule {}
    
  8. Now let's try running our application. In your project command prompt, run:

    ng serve
    
  9. Open our application at http://localhost:4200/.

  10. You will be asked for notification permission. Allow it.

  11. Now open your browser console by inspecting element. You will see your token in there. It means we already configured our application!
    Image description

Checking push notification functionality

  1. Make sure you are still running your Angular project.
  2. Go to Firebase Project Settings.
  3. Go to Cloud Messaging tab.
  4. You will see this section. Image description
  5. In Cloud Messaging API (Legacy) which still disabled, click the kebab menu (the three dots). Image description
  6. Choose Manage API in Google Cloud Console. Image description
  7. You will be redirected to a new tab. Click Enable button. Image description
  8. Back to Firebase Project settings tab. Refresh it. You will see a new generated Server key by default. Image description
  9. Now open Postman. Create new POST request. The endpoint is https://fcm.googleapis.com/fcm/send.
  10. Go to Headers tab.
  11. Add Authorization as key and the value is key=your_server_key. Server key is something that you got from step 8.
  12. Add another headers of Content-Type and choose application/json Image description
  13. Go to Body tab. Choose Raw and JSON then copy this:

    {
        "notification": {
            "title": "New Notification",
            "body": "This is a sample push notification."
        },
        "to": "insert token from Angular project console"
    }
    
  14. Click Send

  15. In Postman, you will see this kind of response:
    Image description

  16. In your Angular project console, you will see a notification coming in at the console:
    Image description

Top comments (1)