Firebase Cloud Messaging with React.js

Shubham Pandey
5 min readJan 16, 2021

--

FCM (Firebase Cloud Messaging) basically helps you receive notifications in various platforms. The FCM SDK is supported only in pages served over HTTPS. This is due to its use of service workers, which are available only on HTTPS sites.

Recently I was in need to integrate a push notification service so that our web client can handle notifications coming and showing them to users. We were already using React , so I’ll be taking you through the journey of how I did that.

Step 1:

  • The first thing needed here is you should have a firebase account.
  • Once you have your account ready, the below image will be your landing screen, here you have to create a project, so do it….
Create a project through the button shown.
You can disable Google Analytics if you don’t need it.
  • As we are integrating with web-app, will create a firebase app for web.
Click on the web icon where the tooltip is shown in the above image.
  • Give a name to your app and click on next, once you register you will get your respective app’s firebase config . Save them somewhere as will need them.
Once you are at the 2nd step it will show you configs.

or you can goto Project Settings > General > Your apps > Firebase SDK snippet > Config and you will get your firebaseConfig information for the project.

Now let’s jump onto coding 🖥

Install Firebase SDK

To integrate firebase SDK with your react app run ->

npm install firebase 
or
yarn add firebase

Connect Firebase Cloud Messaging

After installing Firebase SDK will create a firebaseInit.js in src folder.
Here we will initialize our firebase app with the config of our app from Firebase.
Your configs will look something like this:

{
"apiKey": "your API Key (e.g: ADLICN7-sdun...)",
"authDomain": "yourdomain.com",
"databaseURL": "https://yourdb.com",
"projectId": "yourproject-xyz",
"storageBucket": "your-project-random.com",
"messagingSenderId": "738645738",
"appId": "your app id.",
"measurementId": "X-12468cujk"
}

Content of firebaseInit.js :

import firebase from "firebase"const config = { //This config will be specific to yours
"apiKey": "your API Key (e.g: ADLICN7-sdun...)",
"authDomain": "yourdomain.com",
"databaseURL": "https://yourdb.com",
"projectId": "yourproject-xyz",
"storageBucket": "your-project-random.com",
"messagingSenderId": "738645738",
"appId": "your app id.",
"measurementId": "X-12468cujk"
}
const firebase = firebase.initializeApp(config)
const message = firebaseApp.messaging();
export {message};

This will retrieve us a firebase messaging object which we will use to generate tokens specific to a device. This token identifies which device to send the notification to.

Add this code snippet to whatever component you want to show a popup for notification

import { message } from "../firebaseInit.js";
messaging.requestPermission()
.then(async function() {
const token = await messaging.getToken();
// Token can be sent to server from here.
console.log(token)
})
.catch(function(err) {
console.log("Unable to get permission to notify.", err);
});
navigator.serviceWorker.addEventListener("message", (message) => console.log(message));
})

messaging.getToken() will generate your device token. If notification permission has not been granted, this method will ask the user for notification permissions. Otherwise, it returns a token or rejects the promise due to an error. This token will be sent to the server so that server can identify the device.

Token will look something like this in your console:

elq7U9eiexuXOYkblWpcrG:APA91bHIZvXXlcFZ1tX38ELZ5JBir1EQrDCb7kJRS_JimnIJGOHn87U6qQq0vevGjzJrBPnsdjlaa68139cku3719cKJAIUbka6_seui279scb

Below snippet will add an event listener which will be called when your device receives a message, here you can customize how you want to show notification on your app.

navigator.serviceWorker.addEventListener("message", (message)  => console.log(message));

Register a Service Worker

Service Worker is basically a script that your browser runs in background, which enables features that don’t need any UI/user interaction.

Firebase messaging service needs firebase-messaging-sw.js the file where the worker will run, this file should exist in root level where our files are served.

As we use CRA for react-app, we will add it to public folder of our project.

importScripts("https://www.gstatic.com/firebasejs/5.9.4/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/5.9.4/firebase-messaging.js");
const firebaseConfig = { //This config will be specific to yours
apiKey: "your API Key (e.g: ADLICN7-sdun...)"
y,
authDomain: "yourdomain.com",
databaseURL: "https://yourdb.com",
projectId: "yourproject-xyz",
storageBucket: "your-project-random.com",
messagingSenderId: "738645738",
appId: "your app id.",
measurementId: "X-12468cujk"
};
firebase.initializeApp(firebaseConfig);const messaging = firebase.messaging();messaging.setBackgroundMessageHandler(function(payload) {
const promiseChain = clients
.matchAll({
type: "window",
includeUncontrolled: true,
})
.then((windowClients) => {
for (let i = 0; i < windowClients.length; i++) {
const windowClient = windowClients[i];
windowClient.postMessage(payload);
}
})
.then(() => {
return registration.showNotification("my
notification title ");
});
return promiseChain;
}); self.addEventListener("notificationclick", function(event) {
console.log(event);
});

That’s it, now this service worker will run to show notifications when your app is in the background.

Note:

If you face an error like service worker registration failed .

Try this:

if ("serviceWorker" in navigator) {
navigator.serviceWorker
.register("./firebase-messaging-sw.js")
.then(function(registration) {
console.log("Registration successful, scope is:", registration.scope);
})
.catch(function(err) {
console.log("Service worker registration failed, error:", err);
});
}

This will help you in registering your worker.

Testing Notifications:

You can use curl/Postman for testing the above setup as per your choice.
Below I’ve shown how to test using Postman.

API Details:

Your API result will look something like this.

Headers Format:

  • The authorization will contain your firebase app’s server key.

Steps to find Authorisation Key:

  • Click settings wheel on firebase console:
Click on Project settings
  • Click on Cloud messaging tab.
  • Key will be shown in the tab result as Server Key . Use this key in headers now.

Conclusion

Thanks for reading this!

I hope you now understand how to make use of push notifications and you should not have any difficulties in setting up FCM following the above procedure.

Open to any doubts/ suggestions.

--

--

Shubham Pandey
Shubham Pandey

Written by Shubham Pandey

A traveler and reader working with JS, React, Python, AWS and Serverless

Responses (1)