Handle Push Notification in React in 5 Easy Steps
By: Mohammad Faisal
Tags: JavaScript, Firebase, Notifications, Programming, React

Using firebase push notification

Photo by Luís Perdigão on Unsplash

Notifications are an important part of good user experience. You can keep your users updated about your product and offers by using notification properly .

Today we will see how we can receive notification in our ReactJS web application. I assume you already have a basic react application to follow along. We will use firebase for the notification part.

STEP 1 : Install Firebase Dependency

You should install required dependencies

yarn add firebase

Now go to your firebase console -> create a project -> grab your firebase projects configuration details . You can learn more from here

STEP 2: Add Service Worker to Project

To receive notification we need to have a service worker in our application .

A service worker is a script that your browser runs in the background, separate from a web page, opening the door to features that don't need a web page or user interaction.

As we want to receive notification without any user interaction we need to have a Service Worker . To create one . . .

Go inside your public folder (the folder with index.html file in it)

Create a new file named firebase-messaging-sw.js

Add the following code and replace the value of config object with your configuration values

firebase-messaging-sw.js

STEP 3: Register Service Worker to Handle Background Notification

inside App.js ( or any other component / hook ) add the following code right before rendering the application . It will register the service worker.

After running the application you can go to your devTools from browser and under application > Service Workers to see if the service worker is activated or not.

Browsers dev tools

STEP 4: Add Utility Functions

Now we are ready to receive notification in browser. But we need 2more things.

Permission from user if he wants to view notification or not

Device token to identify our device ( we have to save it somewhere)

Now inside your App.js file add the following code to get the user permission and deviceToken

import firebase from 'firebase' export default function App () { /// ... registration of service worker firebase

.messaging()

.requestPermission()

.then(() => firebase.messaging().getToken())

.then((deviceToken) => {

console.log(deviceToken) // save this token somewhere

})

.catch((err) => {console.log(err)}) return <div> App </div> }

But if you like to keep your code clean you can create a custom hook with all the necessary logic for notification named useFirebaseNotification.js which will be something like this . . .

This hook will register your service worker and ask for permission and get the deviceToken for you .

call this hook from your App.js

export default function App () { useFirebaseNotification() return <div> App </div> }

Much cleaner right ?

STEP 5 : Send Notification from Backend

We are all set for receiving notification in our frontend . We will get notification whether our app is on the foreground or not.

If you have a backend application from where you can handle notifications you can grab the device token from earlier and send a notification .

Or you can send notification from your firebase console also.

From your backend (Which should also be connected to firebase but out of scope for this tutorial ) you can use the following code to send notification. from NodeJS

import admin from 'firebase-admin'; const payload = {

title: 'title',

body: 'body',

data: {

title: 'title',

body: 'body'

},

tokens: [DEVICE_TOKEN]

};



admin

.messaging()

.sendMulticast(payloadWeb)

.then(response => {

console.log(response.responses);

});

Hopefully you can see the notification in your browser. You can do all kind of custom stuff .

That’s it for today. Happy Coding !