Send Web App Notifications with Firebase Cloud Messaging

A tutorial on how you can use Firebase Cloud Messaging to send notifications to your web app users.

Aatif Bandey
JavaScript in Plain English

--

Do you use Amazon, Tokopedia, or Flipkart? Then you must have got some notifications on your browser.

Well, all these messages, and notifications are sent to your mobile phones, desktops, etc via Firebase, and today I will share how we can use Firebase cloud messaging to send notifications to our app users.

What is Firebase Cloud Messaging?

FCM is a messaging solution that lets you send and receive messages in real-time. With FCM you can send notifications, and messages to client devices. It is independent of the platform, you can push messages to the web or native apps too.

FCM offers various methods of distribution, you can send messages, and notifications to a single device or multiple devices.
For more details on how FCM works, you can find them here:

Integrate Firebase Cloud Messaging

FCM works with various frontend platforms like ios, android. But in this article, we will focus on how to use FCM with the web and if you are an Android🤖 or an iOS 🍏 developer.

Bye Bye

Oh, you are a web developer? Congratulations! You have chosen the right career 🤪.

Ok, we know that Firebase is backed by Google, so there are some requirements we need to fulfill:

  • Create a Google account (if you don’t have one 😳).
  • Create a Firebase project at the Firebase console.
  • After creating the app you will land on the Firebase console dashboard.
  • Navigate to Cloud Messaging under Engage.
  • Add Firebase to the web app and register.

Install Firebase using npm

Now let’s get our hands dirty.
Run the below command to install Firebase in your project.

npm install firebase --save

Initialize Firebase in your app.

import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";

const firebaseConfig = {
apiKey: <your-api-key>,
authDomain: "medium-project-9adf6.firebaseapp.com",
projectId: "medium-project-9adf6",
storageBucket: "medium-project-9adf6.appspot.com",
messagingSenderId: "<your-messaging-id>",
appId: <your-app-id>,
measurementId: <your-measurement-id> // should start with G
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
Note: The below steps are shown to set up FCM version 9.

Simply copy the above-shared snippet and paste it to your index.html.
If you are using Next.js or any React framework you can paste it to any entry file in your app, can be app.js or index.js, etc.

Configure Web Credentials with FCM

After the initialization, we will configure credentials.
FCM uses auth keys known as VAPID Keys to authorize send requests.
To subscribe to our app to push notifications, we need to map a pair of keys with our Firebase project. We can generate new key pair through the settings as shown below:

  • Go to Project settings
  • Navigate to the Cloud Messaging tab
  • Generate and copy the key

We have the VAPID key available and we will use it in our project. We will first create a file named firebase-messaging-sw.js and placed it at the root of our domain.
By root I mean we can easily access this file as www.mysite.com/firebase-messaging-sw.js If you are using nextJs place, you can place it in the public folder. This file is required to set up a background notification handler when the browser is not in focus or in the background.

Access the FCM Token

After the app initializes, we need a token required when sending message requests to different push services. The token will be unique for each app instance. FCM token can be changed upon re-installation or when you delete apps, etc.

We can get FCM tokens via getToken() method. Sharing the complete snippet:

import { getMessaging, getToken } from "firebase/messaging";

const messaging = getMessaging();
getToken(messaging, { vapidKey: '<YOUR_PUBLIC_VAPID_KEY_HERE>' }).then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
// ...
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});

After obtaining the token from the client, we can send it to our app server and store it using some API or broadcast interface.

Receive messages

With all the above setup we are in a state to send or push messages to our users. Before going deeper, we should know that there are two types of messages that can be sent to the users, it can be foreground and background messages.

Two important methods run in the background to receive data:

  • onMessage
  • onBackgroundMessage

Implementation

First and foremost we need to register a service worker.

If you don’t know, what a service worker is, read this:

If your app doesn’t use service worker you can use the below snippet to register the same:

const ua = navigator.userAgent;navigator.serviceWorker
.register(`service-worker.js`).then((registration) => {
console.log('Registration successful, scope is:',registration.scope);

Sharing the complete implementation to receive foreground and background messages:

The above code is self-explanatory. In case have any doubt, let's start by reading line #10, here we register a service worker, and from lines #14 — 22, we initialize firebase with available keys.
We are also using two methods onMessage and onBackgroundMessage to receive messages as shown in lines #26 and #31.
You can do an update to your react components or do DOM manipulations inside onMessage callback.
We use showNotification function to pop-out notifications if the window is not in focus.

Finally, everything is set up.

Send your first message

How do we test our notifications? Let’s go back to the Firebase dashboard. Firebase dashboard provides us the ability to send Test Messages to our devices before rolling out to production and you can find the same under the Cloud Messaging menu.

As you can see in the illustration shared, we need to have a title and text to our message as they are mandatory fields. Also, we should have an FCM token of the app or device where we need to send the notification or message.

You can get FCM token from getToken() method.

Just hit the Test button and see the magic. You will receive a notification on your device.

There we go. This is how we can integrate Firebase Cloud Messaging into a web app. Thank you for reading. Clap if you learned something new.

Follow me on Twitter @aatifbandey

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.

--

--