push technology

Web Push Notifications Implementation Using Firebase

Angela Stringfellow Last updated on September 3, 2024

Whether you want to boost user interaction, stay in touch with your customers, or improve retention, push notifications are a clever way to increase engagement. There’s no need to go to the expense of creating a native iOS or Android app: with the proper setup, you can start sending notifications to your customers through their browsers, also known as web push notifications.

Firebase, an app development platform from Google, is one of the most popular ways to set up web app push notifications. Learn why Firebase is a popular choice and how to simplify the notification process using Firebase.

In this article:

Why Use Firebase for Web Push Notifications?

Person looking at smartphone after receiving a web push notification
Photo by Andrea Piacquadio from Pexels

Firebase is a suite of development tools to help developers build apps more efficiently. You can use Firebase to build native apps as well as web push notifications. Many developers love working with this suite because it integrates everything they need for databases, analytics, storage, and hosting without jumping between separate solutions.

Firebase Cloud Messaging (FCM) is a powerful built-in service for managing app notifications. While it requires some technical knowledge, FCM simplifies the notification process. It integrates seamlessly with other Firebase services, making it a cinch for developers to take more advanced actions, like targeting push notifications based on user behavior.

How To Set up Web Push Notifications with Firebase

Developer setting up web push notifications with Firebase
Photo by Christina Morillo from Pexels

Setting up web push notifications with Firebase is much easier than creating them from scratch. Follow these steps to start sending notifications that boost subscriber engagement.

1. Set up and Add Firebase to Your Web App

If you haven’t already, visit your Firebase Console to add a new project. After naming your project, add the Firebase code to your web app. Firebase will give you an SDK snippet, which you’ll need to add to your website.

2. Set up Push Notifications in Your App

Take the SDK and add it to your website HTML file. The HTML should look like this:

<script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js"></script>
<script>
  const firebaseConfig = {
    apiKey: "YOUR_API_KEY",
    authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
    projectId: "YOUR_PROJECT_ID",
    storageBucket: "YOUR_PROJECT_ID.appspot.com",
    messagingSenderId: "YOUR_SENDER_ID",
    appId: "YOUR_APP_ID"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
</script>

Once that’s in place, add the FCM code to your website using JavaScript:

const messaging = firebase.messaging();

3. Set up the Service Worker

You can’t send web app notifications without a service worker. To set one up, create a service worker file titled ‘firebase-messaging-sw.js.’ to handle incoming notifications. The JavaScript will look something like this:

importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/9.0.0/firebase-messaging.js');
 
// Initialize Firebase in the service worker
const firebaseConfig = {
  apiKey: "YOUR_API_KEY",
  authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
  projectId: "YOUR_PROJECT_ID",
  storageBucket: "YOUR_PROJECT_ID.appspot.com",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
};
firebase.initializeApp(firebaseConfig);
 
const messaging = firebase.messaging();
 
// Handle background messages
messaging.onBackgroundMessage(function(payload) {
  console.log('Received background message ', payload);
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: '/firebase-logo.png'
  };
 
  self.registration.showNotification(notificationTitle, notificationOptions);
});

4. Request Permission

All push notifications must have user permission to send messages. You can set this up in your web app’s main JavaScript file:

messaging.requestPermission()
  .then(function() {
    console.log('Notification permission granted.');
    return messaging.getToken();
  })
  .then(function(token) {
    console.log('FCM Token:', token);
    // Save the token to your server or use it to send notifications
  })
  .catch(function(err) {
    console.error('Unable to get permission to notify.', err);
  });

5. Send Notifications From Firebase

Go to Firebase > Engage > Cloud Messaging. Click “Send your first message” and fill out the message details. You’re free to push out the message manually, but if you want to send them automatically, you can set this up using Firebase Cloud Messaging (FCM) REST API:

POST https://fcm.googleapis.com/fcm/send
Content-Type: application/json
Authorization: key=YOUR_SERVER_KEY
 
{
  "notification": {
    "title": "Hello World",
    "body": "This is a notification"
  },
  "to": "FCM_DEVICE_TOKEN"
}

Finally, add this code to your JavaScript file to handle incoming foreground notifications:

messaging.onMessage(function(payload) {
  console.log('Message received. ', payload);
  // Customize notification UI here
});

Don’t forget to test your push notifications before you send them to your users to ensure they look and function as you intended across all devices. With webpushtest.com, you can demo standards-based web push notifications across all platforms, including iOS.

Scaling Push Notifications Beyond Firebase’s Capabilities

Using a solution like Firebase Cloud Messaging is easier than building your own web app notification system from scratch. FCM simplifies the entire process, allowing you to make a scalable notification solution for less hassle.

However, as popular as FCM is, it certainly isn’t the only way to send notifications. MagicBell is, hands down, the easiest way to send push notifications to your subscribers. Our real-time notification inbox unifies all subscriber alerts, from Slack to the web. Sign up for MagicBell to send notifications in as little as an hour.

Frequently Asked Questions

Do I need a server to send Firebase push notifications?

No. You can send notifications from the Firebase Console without your own server. However, you may need a server for more advanced features, like personalized triggers. You can set this up using the Firebase Cloud Messaging API.

How do I handle user token updates in Firebase Cloud Messaging (FCM)?

Firebase handles all user token updates for you. Even so, it’s a best practice to store any token updates on your server when Firebase generates a new one. This ensures your system sends notifications to the right device.

Is there a limit to the number of notifications I can send through Firebase Cloud Messaging?

No. You can send as many notifications as you’d like, although too many will overwhelm your users and lead to more unsubscribes. Firebase limits payloads to 4KB, though, so keep your messages lightweight to avoid errors or delays.