Firebase Cloud Messaging Push Notifications With Angular

Jishnu Saha
6 min readOct 30, 2021

--

Push Notifications

Terminologies

Push notification

Push notifications are notifications that are sent from application publishers and that can be sent any time. We get different types of push notifications in our mobile and web applications. Some common notification we get they are weather updates, sport news, social-media app notifications etc. We get those notifications even if the apps are not in use.

Firebase Cloud Messaging

Firebase Cloud Messaging is a service of google. It is a cross-platform messaging solution that lets us reliably send messages to application users.

Angular

Angular is a web development framework that is widely use for frontend web development. It is a TypeScript-based free and open-source web application framework.

In this article we will see how we can integrate Firebase Cloud Messaging Push Notification with Angular.

Initial Set Up

At first we need node.js. Install it from here if it is not already installed.

Install angular cli

npm install -g @angular/cli

Go to firebase

Sign Up or Log in there

From top right corner click Go To Console

Click Add project and create a new project with desired name

From project overview page create a new web app.

Type desired app name and click Register app.

From bottom click Continue to the console.

Click on the created app name.

Click setting button.

On bottom of General tab keep the config data for future use

Go to Cloud Messaging tab.

Keep Server Key and Sender ID

On the bottom from the Web Push Certification section click Generate key pair and keep the new generated key.

Create Angular Project

Create a new project angular project with ng new command.

ng new af-notification

New project will be created under af-notification directory. Move to af-notification directory.

cd af-notification

Install firebase library for your project

npm install firebase

Create a new file manifest.json in src directory where index.html file exist. Put the Sender ID that is copied from Cloud Messaging tab.

{
"gcm_sender_id": "Sender ID"
}

link manifest.json in the index.html file.

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

To detect new messages from firebase, even if app is closed, our app needs a service worker. Create a new file firebase-messaging-sw.js in src directory where index.html file exist.

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");
firebase.initializeApp({
apiKey: "config data from general tab",
authDomain: "config data from general tab",
projectId: "config data from general tab",
storageBucket: "config data from general tab",
messagingSenderId: "config data from general tab",
appId: "config data from general tab",
measurementId: "config data from general tab"
});
const messaging = firebase.messaging();

Put the config data here that has been collected from General tab on Project Settings page. Check package.json file to see firebase version installed for the project and import that. While writing this tutorial the latest version was 9.17.2

Now we need to add these files in angular.json file.

"assets": [
"src/favicon.ico",
"src/assets",
"src/firebase-messaging-sw.js", // add new
"src/manifest.json" // add new
]

Update Environment files. Add new object name firebase, put the data we got from General tab on Project Settings page. Add a additional field vapidKey which we got by clicking Generate key pair on Cloud Messaging tab.

export const environment = {
production: false,
firebase: {
apiKey: "config data from general tab",
authDomain: "config data from general tab",
databaseURL: "config data from general tab",
projectId: "config data from general tab",
storageBucket: "config data from general tab",
messagingSenderId: "config data from general tab",
appId: "config data from general tab",
measurementId: "config data from general tab",
vapidKey: "generated key pair on Cloud Messaging tab"
},
};

Update app.module.ts file. Add these lines on the list of the import lines

import { environment } from "../environments/environment";
import { initializeApp } from "firebase/app";
initializeApp(environment.firebase);

Update app.component.ts file.

import { Component, OnInit } from '@angular/core';
import { environment } from "../environments/environment";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
title = 'af-notification';
message:any = null;
constructor() {}
ngOnInit(): void {
this.requestPermission();
this.listen();
}
requestPermission() {
const messaging = getMessaging();
getToken(messaging,
{ vapidKey: environment.firebase.vapidKey}).then(
(currentToken) => {
if (currentToken) {
console.log("Hurraaa!!! we got the token.....");
console.log(currentToken);
} else {
console.log('No registration token available. Request permission to generate one.');
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});
}
listen() {
const messaging = getMessaging();
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
this.message=payload;
});
}
}

Update app.component.html file

<div *ngIf="message;">
<h1>{{ message.notification.title }}</h1>
<h2>{{ message.notification.body }}</h2>
</div>
<div *ngIf="!message;">
No Message Arrived
</div>

Our project is ready finally.

Now run the project with this command

ng serve

Let’s check what we have built so far

Go to this link

http://localhost:4200/

Browser will ask for permission to send notification. Click allow.

Now if we inspect the page and go to console we will find that we got a token. That is unique for this browser.

We can see not No Message Arrived on the left, as on app.component.ts file we are outputting this, if our app does not get notification.

Lets Send Notifications

For sending notification, request format will be like this.

curl -X POST \
https://fcm.googleapis.com/fcm/send \
-H 'Authorization: key=SERVER-KEY' \
-H 'Content-Type: application/json' \
-d '{
"notification": {
"title": "First Notification",
"body": "Hello from Jishnu!!"
},
"to" : "GENERATED-TOKEN"
}'

Here SERVER-KEY that is we got from Cloud Messaging tab on Project Settings page and GENERATED-TOKEN that is we got from browser’s console tab.

Let’s set up these in postman.

If our focus is on our application page, while sending notification via postman we will see text changed in our web page like this.

If we change the focus from that page we will see a desktop notification on the right bottom corner like this

So, we are done!!

Feel free to check the GitHub repository here.

--

--