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.
Contents:
- What is a push notification and how it works
- Tools for enabling push notifications in a web application
- How to implement push notifications in a web application
- Step 1: Create a firebase project
- Step 2: Create a service worker
- Step 3: Set messaging subscriptions
- Step 4: Send notifications
- Conclusion
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.
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
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.
- The UI sends a registration request to the message server.
- The message server returns a response with a unique token (session ID).
- The UI shares the token with the applicationโs back end.
- 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.
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:
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.
7. Type in your web applicationโs name and wait for the configuration file to be generated. It will look like this:
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!
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:
<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:
'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 applicationfirebase.initializeApp(FIREBASE_CONFIG)
โ Method for initializing Firebase with given parametersself.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 theoptions
parameter contains a set of parameters that can consist ofbody
,data
, andactions
.self.addEventListener('notificationclick', function (event) { โฆ })
โ Event triggered when a user clicks on the notificationself.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.
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. TheFIREBASE_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:
firebase.messaging()
โ Calling themessaging()
method for the firebase object retrieves aMessaging
service that provides access to the FCM functionality.getToken()
โ Calling this method for theMessaging
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:
- Open the Firebase console.
- Go to the project settings.
- Open the Cloud Messaging section.
- Copy the contents of the Server key field.
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
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:
{
"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:
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:
const admin = require('firebase-admin');
Provide the path to your Firebase service account key:
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:
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.
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!