Integration Of Firebase Push Notifications To Reactjs

Push notifications are one of the effective ways to always be connected to your favorite or frequently used Applications for any in app updates and similarly for the Application providers to connect with their clients. 

Google’s Firebase is one such push service provider, which we will use further in this article. 

First, register your app in the firebase console to get your firebase config object. 

Help Links: 

Setup Instructions : (https://firebase.google.com/docs/web/setup), 
Console : (https://console.firebase.google.com/)

Add a manifest.json file in your public folder add gcm sender id which is unique and the same for all projects as shown below.
{
“gcm_sender_id”:103953800507
}

and link its reference in the index.html file as shown.< !DOCTYPE HTML >
< html lang=”en” >
< head >
< meta charset=”utf-8″ >
< meta name=”viewport” content=”width=device-width, initial-scale=1, shrink-to-fit=no” >
< link rel=”manifest” href=”%PUBLIC_URL%/manifest.json” >
< /head >

Now we have to add a service worker (firebase-messaging-sw.js) file in Public folder to handle notifications when in background as below. Before that install the firebase module.

npm install –save firebase

//public/firebase-messaging-sw.js
import * as firebase from “firebase/app”;
import ‘firebase/messaging’;
const firebaseConfig = {
   apiKey=”API_KEY”,
   authDomain: “PROJECT_ID.firebaseapp.com”, 
   databaseURL: “https://PROJECT_ID.firebaseio.com”,
   projectId: “PROJECT_ID”,
   storageBucket: “PROJECT_ID.appspot.com”,
   messagingSenderId: “SENDER_ID”,
   appId: “APP_ID”,
   measurementId: “G-MEASUREMENT_ID”
};
//Initialize Firebase
firebase.initializeApp(firebaseConfig);
if (firebase.messaging.isSupported()) {
   const messaging = firebase.messaging();
   messaging.setBackgroundMessageHandler(function (payload) {
   return self.registration.showNotification(payload.title, payload.body, payload.data);
});
}

Based on your requirements you can handle receiving messages either in your App.jsx or any other screen by sending your Firebase token to your apps server. Below is the implementation for requesting browser permission to show notifications and get unique tokens.

initializeFirebase=async()=>{
         //Initialize Firebase
         if(!firebase.apps.length){
                 firebase.initializeApp(firebaseConfig);
         }
          if(firebase.messaging.isSupported()){
                     let messaging=firebase.messaging();
                     messaging.requestPermission()
          .then(()=>{
                return messaging.getToken()
           })
           .then(async(token)=>{
                 console.log(‘token’, token)
            })
            .catch(err=>{
                     console.log(err)
             })
            messaging.onMessage((payload)=>{
                        console.log(‘onMessage’, payload)
               })
            })
         }

This is the basic implementation of Firebase push notifications from the front-end side for a React JS Project.

Leave A Comment

Your email address will not be published. Required fields are marked *