Logo
blank Skip to main content

How to Add Web Push Notifications Using Firebase

Displaying push notifications on a website or in a web application is a great way to interact with users, provide timely updates, and boost interaction. Push notifications tell users about important events, offer them customized content, and allow them to interact with an application in one click. However, it can be challenging to choose among the wide selection of push notification tools.

In this article, we discuss the fundamentals of push notifications and provide valuable tips on how to choose the most suitable tool for your web application. Youโ€™ll also discover why and how to use Firebase to efficiently configure push notifications, empowering your web projects while saving your budget.

This article will be useful for tech leaders who are looking to enhance their web applications and are considering implementing Firebase web push notifications.

What is a push notification and how it works

Push notifications are messages that are sent to a userโ€™s device directly from a server, without requiring the user to be actively using an app or website. Such messages usually alert users about important events, new content, or even discounts. They can appear on both mobile devices and desktop computers.

Push notifications allow you to establish communication between your applicationโ€™s server and a website or your client in real time without needing to reload the web page. For instance, push notifications can help users receive customized content and opt in to timely updates by simply clicking on a pop-up window.

example of a push notification

 

Example of a push notification

Modern web applications and websites should enable push technology, since it allows you to:

  • Alert users about important events like upcoming sales or updates
  • Remind users about abandoned carts in online shops or offer discount codes
  • Quickly receive confirmation of usersโ€™ actions
  • Display clickable icons and texts
  • Enable users to interact with your site or app without going back to it
why implement push notifications in a web application

Letโ€™s take a look at the push notification workflow.

When a web application is launched, a clientโ€™s user interface (UI) sends a request containing user data to the message server. The message server then saves all necessary user data in its database, generates a session ID token for the user, and sends this token to the clientโ€™s UI, which in turn sends the token to the application backend. The web applicationโ€™s back end will use the token to send notifications to the user.

push notification workflow

 

Push notification workflow

  1. The UI sends a registration request to the message server.
  2. The message server returns a response with a unique token (session ID).
  3. The UI shares the token with the applicationโ€™s back end.
  4. The back end can raise a notification event anytime it wants using the token by calling the message server notification endpoint. The message server will then push new events to the client UI.

Looking to enhance user engagement on your web application?

Let’s discuss how our business analysts and software development experts can drive your productโ€™s success!

Tools for enabling push notifications in a web application

There are a lot of tools for configuring push notifications for web applications. The most popular are:

  • Webpushr. This tool is free for up to 10,000 subscribers. For more than that, the price starts at $29 per month for up to 50,000 subscribers and grows alongside the number of subscribers. Webpushr offers a WordPress plugin and supports all popular browsers such as Chrome, Firefox, Safari (macOS only), Microsoft Edge, and Opera.
  • Pushnami. This platform offers web push notification functionality with pricing starting at $0.01 per subscriber. Pushnami supports all major browsers (Chrome, Firefox, Safari , Microsoft Edge, and Opera), as well as Android and iOS devices.
  • OneSignal. This tool allows you to send messages through desktop and mobile browsers. It supports all major browsers including Chrome, Firefox, Safari, Microsoft Edge, and Opera. OneSignal offers a free plan with limited functionality and the opportunity to send notifications to up to 10,000 recipients per message. Paid plans start from $9 per month.
  • Pushbots. This tool offers push notification functionality with a free plan available for up to 1,000 subscribers and no credit card or other commitment required. Commercial plans start from $29 per month for up to 5,000 subscribers. Pushbots also offers an SDK for WordPress and supports major browsers like Chrome, Firefox, and Safari.
  • Google Firebase. This is a comprehensive platform for creating mobile and web applications that can also be used for sending push notifications. Firebase allows you to group up to 500 messages into a single batch and send them all in a single API call. The tool is free irrespective of the number of subscribers, and it supports Firefox, Chrome, Safari, and Edge. You can check supported environments for the Firebase JavaScript SDK on the official website.

For this article, we use Firebase as our messaging server. Firebase offers lots of functionality, including a server, database, hosting, Firebase Cloud Messaging (FCM) server, and authentication. While Google Firebase offers a free tier with no subscriber limits, it also provides additional paid plans for projects requiring more advanced features.

Letโ€™s take a look at its pros and cons.

firebase pros and cons

Now letโ€™s explore how you can add push notifications to a web application with Firebase.

How to implement push notifications in a web application

Letโ€™s explore how to enable push notifications in your web application using Firebase in four steps:

add push notifications to a web application in 4 steps

Step 1: Create a Firebase project

Start with building a new project in the Firebase platform. Hereโ€™s what you need to do:

1. Register with Firebase. You can use your Google account for this.

2. Go to the Firebase console page.

3. Click Create a project (or Add a project if youโ€™ve worked with Firebase before).

4. Specify the project name, choose a location, and wait for your project to be created.

5. Wait for the application console to open.

6. Click the button to create a web project.

button for creating a project

 

Button for creating a project

7. Type in your web applicationโ€™s name and wait for the configuration file to be generated. It will look like this:

firebase configuration file

 

Firebase configuration file

8. Copy the configuration code. Youโ€™ll need it during the following steps.

Note: Your web application or website must support the HTTPS protocol. Otherwise, you wonโ€™t be able to launch push notifications.

Alternatively, you can use the Firebase CLI tool to create and manage projects more efficiently from the command line. Hereโ€™s how you can do it:

1. Install the Firebase CLI via npm:

npm install -g firebase-tools

2. Log in to Firebase.

3. Initialize Firebase in your project. Go to your project folder or create a new one and run the following command to set up Firebase:

firebase init

4. Choose services during the initialization process. You will be prompted to select Firebase services like Firestore, Functions, and Hosting. For push notifications, select Firestore and Firebase Hosting if needed.

5. Create the project directly from the CLI by running the following code:

firebase projects:create your-project-name

6. Configure the project. The Firebase CLI will create a firebase.json configuration file and necessary setup files in your project directory. Once completed, the CLI will sync your project with the Firebase Console.

This method will also generate a configuration code that you will need in the next steps.

Read also

How to Implement the Places API in Your Web Application

Discover how to implement location-based features, enhance user experience, and create new engagement opportunities in our guide! 

Learn more

Step 2: Create a service worker

A service worker is a script that runs separately from your website in the background. When working with push notifications, a service worker is responsible for configuring the background notification handler for situations when a browser is in background mode. In all cases, for push notifications to work, a web page should handle the onMessage callback.

Note: In the examples below, we use the index.html page.

Now that you have the Firebase configuration file, you can add a service worker and the Firebase SDK to the clientโ€™s UI:

1. Add the following to your web applicationโ€™s HTML code and place it where you want to initialize the message:

HTML
<script src = "https://www.gstatic.com/firebasejs/8.3.2/firebase-app.js" > </script> 
<script src = "https://www.gstatic.com/firebasejs/8.3.2/firebase-analytics.js" > </script>

This code is responsible for adding JS scripts. You can find it in the configuration file code generated in Step 1.

2. In your web applicationโ€™s root, create a service worker and name it firebase-messaging-sw.js. Youโ€™ll need this service worker to receive and handle incoming messages.

3. The content structure of the service worker will look something like this:

JavaScript
'use strict';
 
importScripts("https://www.gstatic.com/firebasejs/8.2.4/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/8.2.4/firebase-messaging.js");
 
const FIREBASE_CONFIG = {
	apiKey: "",
	authDomain: "",
	projectId: "",
	storageBucket: "",
	messagingSenderId: "",
	appId: "",
	measurementId: ""
};
 
// Initialize the firebase in the service worker.
firebase.initializeApp(FIREBASE_CONFIG);
 
self.addEventListener('push', function (event) {
	var data = event.data.json();
 
	const title = data.Title;
	data.Data.actions = data.Actions;
	const options = {
		body: data.Message,
		data: data.Data
	};
	event.waitUntil(self.registration.showNotification(title, options));
});
 
self.addEventListener('notificationclick', function (event) {});
 
self.addEventListener('notificationclose', function (event) {});

4. Update the FIREBASE_CONFIG constant according to your configuration file.

5. Register the new firebase-messaging-sw.js service worker in your application.

Letโ€™s explore the structure of the newly created service worker in detail:

  • importScripts โ€” Section for adding scripts to the web application
  • firebase.initializeApp(FIREBASE_CONFIG) โ€” Method for initializing Firebase with given parameters
  • self.addEventListener('push', function (event) { ... }) โ€” Event that occurs on the client side when a new notification is received. Usually, displaying the notification to the client occurs in the body of this method.
  • event.waitUntil(self.registration.showNotification(title, options)) โ€” Event that is in charge of displaying the notification window. The title parameter holds the notifictionโ€™s title and the options parameter contains a set of parameters that can consist of body, data, and actions.
  • self.addEventListener('notificationclick', function (event) { โ€ฆ }) โ€” Event triggered when a user clicks on the notification
  • self.addEventListener('notificationclose', function (event) { โ€ฆ }) โ€” Event triggered when a user closes the notification

Read also

Building a Cross-Platform Mobile Web Application with Ionic and Angular

Leverage cross-platform frameworks to create responsive, feature-rich apps that reach a wider audience. 

Learn more

Step 3: Set messaging subscriptions

Now, letโ€™s configure messaging subscriptions between the UI and the Firebase message server:

  • The firebase.initializeApp(FIREBASE_CONFIG) line in the service worker is responsible for registering the client in the message server. The FIREBASE_CONFIG parameter is responsible for Firebase configuration parameters. Basically, this line is responsible for user registration in the message server.
  • Youโ€™ll also need the firebase.messaging().GetToken() line to receive a token (session ID), which youโ€™ll later send to the back end and save to the database to generate new notifications.

We can logically divide the firebase.messaging().GetToken() line into two operations:

  1. firebase.messaging() โ€” Calling the messaging() method for the firebase object retrieves a Messaging service that provides access to the FCM functionality.
  2. getToken() โ€” Calling this method for the Messaging service allows you to receive the token (session ID).

Step 4: Send notifications

At this step, all elements are ready. Letโ€™s explore how exactly you can send a notification to the end user when you already know their token.

First, you need to get a service key. To do that, you need to perform the following steps:

  1. Open the Firebase console.
  2. Go to the project settings.
  3. Open the Cloud Messaging section.
  4. Copy the contents of the Server key field.
copying a server key

 

Copying a server key

Letโ€™s use the Postman platform to practice sending push notifications. Hereโ€™s what you need to do:

1. Set the POST request type.

2. Enter the following URL: https://fcm.googleapis.com/fcm/send

3. Add two Headers:

  • Authorization: serverKey, which is the key you copied earlier
  • Content-Type: application/json
adding headers

 

Adding headers

4. Add the Body option to your request, where User token is the token that Firebase retrieved during user registration in Step 3. The request will look something like this:

JavaScript
{
 "notification": {
   "title": "Notification title", 
   "body": "Notification body"
 },
 "to" : "User token (session id)"
}

5. Finally, you can send the request.

After that, the server will push notifications and they will be displayed on a userโ€™s screen.

Note: During a clientโ€™s first attempt to receive a notification, the web browser will ask the user for permission to receive notifications. It looks like this:

request for permission to receive notifications

 

Request for permission to receive notifications

If the user blocks notifications, the request for permission will not be shown upon the next attempt to send a push notification. In this case, push notifications can only be displayed if the user changes the corresponding permissions for the web page in the browser settings.

Developers often use Firebase Admin SDK to send push notifications from a server. Hereโ€™s an example of how you can send a message using the Firebase Admin SDK:

1. Install the Firebase Admin SDK using npm:

npm install firebase-admin

2. Set up Firebase Admin in your project. First,  initialize the Firebase Admin SDK in your Node.js application:

JavaScript
const admin = require('firebase-admin');

Provide the path to your Firebase service account key:

JavaScript
const serviceAccount = require('path-to-your-service-account-file.json');


admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

3. Once Firebase Admin is set up, you can send a message to a specific user using their registration token:

JavaScript
const message = {
  notification: {
    title: 'Notification Title',
    body: 'Notification Body',
  },
  token: 'user-device-token'
};


admin.messaging().send(message)
  .then((response) => {
    console.log('Successfully sent message:', response);
  })
  .catch((error) => {
    console.error('Error sending message:', error);
  });

Here, the token represents the userโ€™s device token retrieved during the registration process in Step 3.

This method of sending notifications using the Firebase Admin SDK is particularly useful for developers working on server-side notification handling.

As you can see, using Firebase Cloud Messaging as a messaging server for configuring push notifications is straightforward and easy. You can find more information on its functionality in the Firebase documentation.

Related project

Developing and Supporting a CRM System for a Medical Transportation Company

Discover how Apriorit helped streamline workflows, enhance customer interactions, and drive growth for our client with our tailored CRM development and support services.

Project details

Conclusion

Configuring and using push notifications is quite a simple process that doesnโ€™t require too many resources. Meanwhile, it covers a significant number of clientโ€“server interactions.

At Apriorit, we use a variety of tools for push notification functionality in order to make your web applications more user-friendly and efficient. Web push notifications implementation using Firebase is one of our top choices because of its ease of use, scalability, and cost-effectiveness.

At Apriorit, we have an experienced team of web application developers ready to help you with projects of any complexity.

Looking for web development experts?

Partner with Apriorit to elevate your online presence and create tailored solutions for your business growth! 

Have a question?

Ask our expert!

Maryna-Prudka
Maryna Prudka

R&D Delivery Manager

Tell us about your project

Send us a request for proposal! Weโ€™ll get back to you with details and estimations.

Book an Exploratory Call

Do not have any specific task for us in mind but our skills seem interesting?

Get a quick Apriorit intro to better understand our team capabilities.

Book time slot

Contact us