Progressive Web Apps

How to Integrate Push Notifications Into Your PWA

Push notifications is, undoubtedly, the key factor that separates Progressive Web Apps from regular web applications, determinant of your app conversion rates. However, it seems that not all PWAs are integrated with push notifications, which is a strange thing considering it’s one of the most effective ways to engage your users.

It’s for these reasons that in our tutorial today, we will be showing you how to integrate Push Notifications into your Progressive Web App using Firebase.

Progressive Web Apps and Push Notifications

Since the Progressive Web App is that of an ever-changing movement, it’s hardly surprising to see that the technology itself has become on-par (function-wise) with its native app counterpart.

Recommended reading: PWA vs Native: Which Suits You Better? 

Notification triggers give developers the ability to schedule notifications, even if the user’s device is on airplane mode.

Jon Krafcik, Chrome Dev Summit 2019
Push Notification Triggers - Chrome Dev Summit 2019
New in Chrome 80, Notification Triggers enable notifications even in airplane mode

With all these radical changes in-place, it would be a waste not to take advantage of it to drive even more revenue to your PWA. And it isn’t even something overly complicated as you could easily set up a Push Notification function of your own using this tutorial.

Recommended reading: 9 Must-Have Features of a Progressive Web App (PWA) for E-Commerce

How to integrate Push Notifications into your PWA

In our tutorial today, we’ll be integrating Push Notifications into a PWA using Firebase, specifically the Cloud Messaging feature within it which enables sending of messages using HTTPS requests.

Prerequisites

  • A Firebase account (since you will be creating a project within Firebase)
  • A Progressive Web App. For a simplified demonstration, we’ll be using a create-react-app which can be created by using one command, but the method that we will be using can be used on any JavaScript-based project. This PWA tutorial guides you through the steps of creating a Progressive Web Application using React, Node.js and Firebase.
PWA Push Notifications: Create a Firebase project
Create a project with Firebase

Note: Once you have your PWA or React web app set up, you need to add the Firebase library into it using:

npm install firebase --save

Create your push-notification.js

The next step is to create the module that will be in charge of all your notification processings.

First, let’s create a function that initializes Firebase and passes the keys of your project.

import firebase from 'firebase';

export const initializeFirebase = () => {
  firebase.initializeApp({
    messagingSenderId: "your messagingSenderId"
  });
}

Now that you have created the function in charge of all notification processing, you need to import and call it:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { initializeFirebase } from './push-notification';

ReactDOM.render(<App />, document.getElementById('root'));
initializeFirebase();

To get your Firebase key/SDK, simply go to Project Overview → Project Settings and click on this icon:

Firebase SDK for PWA Push Notification

This will direct you to another page which contains the Firebase SDK for your PWA:

Firebase SDK

Notice the messagingSenderId field in the Firebase SDK above. We’ll need the value from this field to replace it to:

messagingSenderId: "your messagingSenderId"

Service Workers

Service Workers is the name of the technology behind a Progressive Web App, which power its offline capability, push notifications and resource-caching.

SimiCart, All You Need to Know About Progressive Web Apps

A service worker is required for the receiving of the onMessage event. By default, Firebase automatically looks for a file called firebase-messaging-sw.js. This can, however, be modified using:

export const inicializarFirebase = () => {
  firebase.initializeApp({
    messagingSenderId: 'your messagingSenderId'
  });
  
navigator.serviceWorker
    .register('/my-sw.js')
    .then((registration) => {
      firebase.messaging().useServiceWorker(registration);
    });
}

By modifying the startup code of Firebase, you can specify which service worker will do the work of importing the scripts needed to show push notifications when your app is running in the background.

Next up is adding firebase-messaging-sw.js to the directory where your files are served. Since ours is a create-react-app, the .js will be going in our public folder:

importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');

firebase.initializeApp({
    messagingSenderId: "your messagingSenderId again"
});

const messaging = firebase.messaging();

If you have not heard about PWA Service Worker yet, we have an exclusive article for you to learn all about this amazing technology.

Requesting user permissions to send notifications

It’s the age of privacy, and you don’t want to annoy your users by sending unwanted and unauthorized notifications!

To request your user’s permission, simply add this to your push-notification.js:

export const askForPermissioToReceiveNotifications = async () => {
  try {
    const messaging = firebase.messaging();
    await messaging.requestPermission();
    const token = await messaging.getToken();
    console.log('user token:', token);
    
    return token;
  } catch (error) {
    console.error(error);
  }
}

And since this function will need to be called from somewhere, we’ll add it at the click of a button:

import React from 'react';
import { askForPermissioToReceiveNotifications } from './push-notification';

const NotificationButton = () => (
    <button onClick={askForPermissioToReceiveNotifications} >
      Click to receive notifications
    </button>
);

export default NotificationButton;

Send Push Notifications to a user token

In this step and any of our step that involves direct sending of push notifications, we’ll be using Postman to send notifications using Firebase’s Cloud Messaging service.

The Firebase API needs to be informed of any token that the user receives, which is why a POST request (to https://fcm.googleapis.com/fcm/send ) is needed. This request will contain a JSON whose content is as follows:

{
    "notification": {
        "title": "Firebase",
        "body": "Firebase is awesome",
        "click_action": "http://localhost:3000/",
        "icon": "http://url-to-an-icon/icon.png"
    },
    "to": "USER TOKEN"
}

To start off, you need to set the appropriate Headers for your Postman configurations:

Postman also requires you to identify the SERVER_KEY and Content-Type of your project:

Content-Type: application/json
Authorization: key=SERVER_KEY

Note: The SERVER_KEY can be found under the Cloud Messaging tab in Firebase settings:

Firebase Cloud Messaging - Server Key

You can now send notifications to one device at a time!

PWA Push Notifications: Sending notifications to one token

Notes: These notifications only appear when the app is in the background or minimized.

Send Push Notifications to a group of users

The above demonstration was for sending notifications to one user only, but what about sending it to multiple users? That’s when a featured from Firebase, topic, comes into play. With topic, you can send one request containing a specific topic to multiple tokens at a time.

To do this, simply send a POST request to the address:

https://iid.googleapis.com/iid/v1/TOKEN/rel/topics/TOPIC_NAME

with TOKEN and TOPIC of your preference.

Note: Don’t forget to include the same Cloud Messaging key that we used earlier.

Pushing notifications to multiple users is almost the same as pushing it to one user. The only difference is that you’d need to change the value of the to to topic names instead of tokens.

{
    "notification": {
        "title": "Firebase",
        "body": "Firebase topic message",
        "click_action": "http://localhost:3000/",
        "icon": "http://localhost:3000/icon.png"
    },
    "to": "/topics/TOPIC_NAME"
}

And that’s it! You should now be able to send push notifications to your selected users using the abovementioned method.

PWA Push Notifications: Sending notifications to one topic

Conclusion

We hope that after this guide, you can now confidently set up a push notification function of your own. Being a new technology, Progressive Web Apps sure is a complicated thing for non-tech-savvy users, which is why there are readily available solution providers such as SimiCart who can take care of your every need with our years of experience in PWAs.

Is it helpful?

A content writer with a passion for the English language.

Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Rohit Martires
Rohit Martires
5 months ago

get u please share the github link

Hesam Marshal
2 months ago

Hi,  I am a newbie in React. I tried to learn push notification with your tutorial. I was not successful, because it is not clear in many steps.  e.g: This will direct you to another page which contains the Firebase SDK for your PWA: after that, you don’t say all [arts of the code should be getting and paste somewhere, or some code only. Suddenly you said: add an event to a button, no any information where the code of button should be. then: You can now send notifications to one device at a time! I am as a newbie, cant figure… Read more »