Firebase Cloud Messaging

Mariappan
6 min readNov 12, 2020

--

Setting up firebase notifications for your PWA app

In this blog, we’ll see a brief on Firebase Cloud Messaging, how to set up push notifications for your PWA. We’ll set up browser notifications for a Next PWA listening for both foreground & background messages.

What are Progressive Web Apps?

The web has evolved a long way from static pages. Today one can easily run their entire business on the web seamlessly. Customers can visit your website on any platform of their choice. With the advent of smartphones, creating web apps should ensure a lot more than interfaces. You need to ensure a smooth experience for users visiting in different screen sizes with devices of your choice, utmost availability, and offline support as well. Not all would have an active internet connection. This gave rise to Progressive Web Apps.

There are chances you might have already used a PWA. Ever noticed some applications work even without active internet connectivity? Ever noticed an Add to home screen banner in your favorite E-commerce websites?

Progressive Web Apps could give the exact smooth experience just like a native app. By creating a PWA your business could deliver a rich experience for anyone, anywhere, on any device with a single codebase. Businesses can easily succeed if they managed to deliver a web experience close to native apps.

Key features of progressive web apps:

  • They are installable
  • Single codebase — supports multiple platforms
  • Offline first — you would be able to see a minimal UI and walk around even when there is no active internet connectivity.
  • Splash screen(on startup) and icon just like native apps
  • Push notifications

How do push notifications help?

Before getting into the details of firebase cloud messaging, let’s find out why push notifications are important for your PWA, and in what cases they can be really helpful.

Visit any popular website on your browser, you will definitely notice a prompt from those applications asking for permission to send notifications to your browser.

Push notifications can help you keep your customers engaged. Say, you have a number of tabs open on your laptop. It can be painful to constantly switch across tabs/windows to stay updated with your services. Chances are high that you will end up missing important messages sometimes.

Instead, if you are getting notified on background, click up and dive deep if needed, can be a huge lifesaver.

What kind of applications makes use of push notifications to a good extend?

  • E-commerce apps like Flipkart, amazon — you can notify users on offers, order status, new product launches, and many more.
  • Food delivery apps like Swiggy, Zomato
  • Streaming platforms like Netflix, Amazon prime
  • Ride booking app — ola, uber, etc.
  • Hotel chains like Airbnb, Oyo, etc.

This list will keep going on.

Firebase Cloud Messaging

Firebase cloud messaging is a cross-platform messaging solution from Google. With FCM one can reliably send and receive messages for free.

It’s super simple to set up notifications with firebase for any platform of your choice.

Setting up Firebase Client Messaging on client app

We’ll explore the steps to configure Firebase Cloud Messaging for a Next.JS PWA app.

FCM lets you receive messages in a browser that supports the Push API. The Push API helps in sending push messages to a web application via a push service. You can read more about it here.

Note: The SDK supports only web pages served under HTTPS.

To get started, First we need to add Firebase to the project.

Adding firebase to a project

  • Sign in to Firebase using your Google account.
  • Create a Firebase project (choose services that your app would make use of — you’ll be given options including analytics, messaging, cloud functions, and so on)
  • Register your app with Firebase. That’s it on the firebase console end.
  • Now, move on to your project directory. The first thing to do is to add the Firebase SDK and initialize it on the root.

To install,

yarn add firebase (or) npm install --save firebase

But, it’s advised to use imports when you are working with frameworks like Next.JS. Thus we’ll use import statements and import specific firebase products needed.

In our case, we will require the firebase app and firebase messaging.

The initialize firebase in your app,

More info about the config object

To initialize firebase in our app, the first thing we would require is to provide firebase configurations. A typical config object structure looks like this,

Here, apiKey, projectId, and appID — are essential configs

measurementId — is related to analytics

messageSenderId — you’ll get if enabled firebase cloud messaging.

One can anytime access any of the firebase products using Namespaces provided by firebase. Say, for example, to use firebase messaging we can simply call by,

firebase.messaging()

Configuring web credentials with FCM

This is one core thing you would require to set up FCM in your app. In order to authorize each request, you would need an id called VAPID (Voluntary Application Server Identification). You can generate a key pair directly from the firebase console under the web configuration section.

The initialization function could look like,

As said before, you should first ask users if they wish to subscribe to notifications. So to request firebase notification permissions,

You can handle message requests in both the foreground and background. That would be a perfect user experience.

Types of firebase messages

  • foreground (when the app is in focus — when you are on the same page)
  • background (when you are in the background, hidden behind other tabs, or completely closed)

Dealing foreground notifications

Prior to setting up this, you will need a firebase-messaging-sw.js file. Here is where we will define the Firebase messaging service worker. This goes into the public folder. To handle messages in the foreground,

Likewise, to handle messages from the background,

Note: Make sure to initializeFirebase and requestFirebaseNotificationPermission before it

Sending messages from the client app

Basically, we need to make a simple HTTP POST request to https://fcm.googleapis.com/fcm/send by sending a JSON in the request body.

JSON passed on the body

The JSON passed on the body would typically look like this,

Header format

You need to pass two essential key pairs on the header.

The final request format should collectively look like,

And, additionally, you should add your gcm_sender_id (you can find it in the config object as well) to the manifest.json file.

{
"gcm_sender_id": "YOUR ID HERE"
}

Also, ensure your service worker is registered at the start. You can typically do it on _app.js a file like this,

Next.JS official documentation provides us with excellent example repo on working with Firebase cloud messaging. Feel free to check the repo link below for the complete flow.

To test your first message with the above implementation, follow this reference.

You can also test via postman referring to the request format discussed above.

Get an example postman collection here.

Note: Make sure to replace the variable over there with your credentials

This is how we can make a web app listen for messages in the foreground and background. Thus we have discussed briefly on firebase cloud messaging, types of messages, and how to work with it from your client app.

If you have any suggestions, need some help/doubts, or wish to discuss more on this topic please write to me at mariappangameo@gmail.com. I’d also love to connect with you all on Linkedin.

--

--

Mariappan

I am a passionate web engineer love to experiment and keep myself updated with technologies and trends. http://mariappan.netlify.com/