Tutorial: Web Push notification using Firebase

Ken
8 min readApr 26, 2021

Another Step towards Progressive Web Application

Progressive Web App (PWA) is defining the future form of the web app. Google has predicted that PWA is going to replace a lot of mobile apps in the coming 2–3 years. It’s not a surprise that the founder of Tapzo’s summarized in his article The mobile app industry’s worst-kept secret has reflected that lack of storage is the main reason 60–80% users are uninstalling the native mobile app within 90 days.

In comparison to the web app, a mobile app can access to the mobile native features like push notification, camera and others that the web app does not have. Well, the great news is, with the arrival of PWA, the web app is now finally able to access more native features.

Let’s dive in to learn one of the very key benefit PWA is offering: engagement.

Push Notification In The Web App

Push notification has been one of the effective ways to improve retention rate and increase user engagement. The timely received push notification reminds users to react to online messaging, go to check out the cart before the offers and sales end, and even to notify users that their kingdom is under attacked by the enemy player so users can react before it’s too late.

The magic of the push notification is that it allows the devices to get the update from the server without draining your battery. Once you have enabled the push notification, you can receive the alert even without visiting the website.

Example: How a Marketing Site keep us more engaged

neilpatel.com is one of the SEO marketing sites which has made good use of the push notification. Once you allow the site to send you notifications, you will see the pop-up notification first thing you open the Chrome browser, which shows you the newest blog from the site on the daily basis. This improves our engagement with the site by more than 50% than in the past.

Therefore, you need to have push notification for your web app. It is not that difficult to enable it, and we will show you the detailed step by step how to develop a push notification demo web app very shortly.

What’s Firebase Cloud Messaging

Firebase Cloud Messaging (FCM) is a service offered by Google to let you relay server messages to registered devices and web app. FCM service is free of charge with some limitations. The size is limited to 2KB or 4KB depending on the type of data, and the message will be kept for a default duration of 4 weeks before it gets deleted.

FCM offers an array of helpful tools to help you create the right engagements with users. You can create A/B testing to see what are the optimal wording and presentation to use. You can study the users’ behaviour via the analytics data provided.

Firebase Predictions is the latest and perhaps the most exciting features added the to platform. Predictions apply Google’s machine learning to your analytics data to predict the users’ likely action based on users’ behaviour.

For an example of a game app, a user who is likely to spend money to upgrade the game equipment, when he/she fail to pass the stage, the app will offer the option to let the user purchase more advanced equipment to continue the game. On the other hand, for free players, the app will trigger an advertisement to let the user watch to continue the game.

Demo Tutorial

In the following, we will walk you through an easy to follow tutorial on how you can enable push notification using FCM. We will also share with you some of the small tips on what to take note of so you can have this up as quickly as possible.

Tutorial Step 1: Register Firebase account

Head to Firebase site and click “Go To Console”. Once signed in you will see the following page. Click “Add Project” to create a new project. Give your project a name, and choose the country/region that reflects your currency and revenue reporting.

Firebase Console

Tutorial Step 2: Getting your Project & Web App Credentials Info

(Updated: 23 Jul 2020) The recent Firebase’s update requires the user to register the web app, as you will need the `appId` value. Give the web app a name, then click next and you will get your config like this. The config can be retrieved from “Your apps” section in the Project Setting as well after you have created it.

Firebase Web App Registration

Now, Click on the cog icon beside the “Project Overview” at the top left > choose “Project Settings”. Then click on “Cloud Messaging” on the settings page like below. Take note of the Server Key and Sender ID, you will need this later. You can ignore the “Legacy server key” and use “Server Key”. Otherwise. you will face a problem when running the curl to test sending the notification.

Cloud Messaging Server Key

Tutorial Step 3: Create the Simple HTML

Without further ado, let’s start writing the simple HTML code. The page will show us the token and any message sent by the Firebase to us later.

Tutorial Step 4: Initialising Firebase and Creating Service Worker JS

Then you have to include the firebase.js. Remember to replace your “sender ID” as the value for messagingSenderId field. After that, you can initialise Firebase.

Next, copy the following to `firebase-messaging-sw.js` and place it to the root of the web folder, this will create the service worker.

Without the file `firebase-messaging-sw.js`, you will get following error

```
; FirebaseError: Messaging: We are unable to register the default service worker.
Failed to register a ServiceWorker: A bad HTTP response code (404) was received when fetching the script. (messaging/failed-serviceworker-registration).

Tutorial Step 5: Requesting permission from Device

We have to make a request explicitly to the user that we want to send him/her notification and get the permission from the user before able to do so.

const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});

If you start a local server and serve the code above, you will get the request prompt like the following screenshot.

Tutorial Step 6: Getting device token

After the user grant permission for us to send the notification, we can get an FCM registration token that can be used to send push messages to this user. For the sake of the simplicity of this demo app, we do not store the registration token in the database. We will modify the previous function to get the token and print it on the web page.

const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted."
console.log("Notification permission granted.");
// get the token in the form of promise
return messaging.getToken()
})
.then(function(token) {
// print the token on the HTML page
TokenElem.innerHTML = "Device token is : <br>" + token
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});

Below is the screenshot you will see if you run the local server to check your code. The registration token (example: csxYa…jR4RI) is a long string of text. You will need this token for the next step.

Device Token after user grants the permission

Tutorial Step 7: Test sending push message

By now, you are all set to send a push message to your web app! There are two ways to test sending message to the device.

A) Using Firebase Console

Go to Engage > Cloud Messaging, then click ‘New Notification’.
Enter the title and text, then click on `Send test message`.
Paste the device token you have gotten earlier, then click ‘Test’.
If everything is set up properly, you will see the push notification showing up.

B) Using Curl
Replace your API_ACCESS_KEY and the DEVICE_REGISTRATION_TOKEN we obtained just now. You can get your API_ACCESS_KEY by clicking on the “Authentication” under “Develop”, then click on the “WEB SETUP” on the top right.

success response after running curl command

When your app is in the foreground, i.e. the user is currently viewing the web page, you can receive and notification directly on the page. For this example, we display the whole notification payload like in below

Receiving notification when web app is in the foreground

However, if your app is in the background, the message received will trigger a display notification in the browser like the screenshot below. You can specify what action to perform if the user clicks on the notification as well. For example, to open the browser and load the site. Nevertheless, this behaviour can be changed.

push notification when app in background

The Complete Solution

Here’s the complete code based on what we have discussed so far. You can also get the source code from GitHub via this link.

If you are facing issue to get it running, you might also check with messaging example in Firebase quickstart-js. Official source code get updated quite frequently.

Change Log

26 Apr 2021

Github example update. Added description of how to send test message via Firebase Console.

23 Jul 2020
The Github example has been updated to user Firebase 7.16.1. There’s some breaking change in the firebase-sw.js as well. So if you get a blank response or error, try to get updated the example source code again.

15 Mar 2020
There’s some breaking change from the recent Firebase update on v7.0.0 Previously, having `{messagingSenderId: ‘xxx’}` was sufficient config for firebase messaging, Now, all of these `(apiKey, projectId, appId)` are needed too. Otherwise, you will be getting an error.

This is a blog repost from https://www.itwonders-web.com/blog/push-notification-using-firebase-demo-tutorial

--

--