Back to blog
May 16, 2025
4 min read

How to Add Push Notifications to Your Web App with Firebase

Push notifications can significantly boost user engagement. Learn how to implement them in your web app using Firebase Cloud Messaging (FCM).

How to Add Push Notifications to Your Web App with Firebase

Push notifications are a powerful way to re-engage users, drive traffic, and deliver timely information directly to users’ devices , even when they’re not actively browsing your site. While once exclusive to mobile apps, web push notifications are now supported in most modern browsers and can be implemented quickly using Firebase.

Firebase Cloud Messaging (FCM) provides a simple, reliable service for sending notifications across platforms. In this guide, you’ll learn how to set up push notifications in your web app using Firebase , from configuration to client-side integration.


Why Use Firebase Cloud Messaging?

Firebase Cloud Messaging is free, easy to integrate, and works across Android, iOS, and the web. It handles the heavy lifting of device registration, message routing, and delivery. For web apps, it supports key features like:

  • Sending messages to specific users or devices
  • Topic-based targeting
  • Scheduled or triggered messages
  • Customizable payloads for rich notifications

With minimal setup, you can start delivering notifications that enhance user engagement and improve retention.


Step 1: Set Up a Firebase Project

If you haven’t already, create a project in the Firebase Console.

  1. Click Add Project and follow the prompts.
  2. Once your project is ready, click Project Settings.
  3. Under the Cloud Messaging tab, note your Server key and Sender ID , you’ll need them later.

Then, add a web app to your Firebase project:

  1. In your project dashboard, click </> Add App.
  2. Register your app and copy the Firebase SDK config object.

Step 2: Install Firebase SDK

Add Firebase to your project using npm or include it via CDN:

npm install firebase

Or in your HTML:

<script src="https://www.gstatic.com/firebasejs/10.0.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/10.0.0/firebase-messaging.js"></script>

Step 3: Initialize Firebase and Request Permission

In your JavaScript entry point (e.g., main.js):

import { initializeApp } from "firebase/app";
import { getMessaging, getToken, onMessage } from "firebase/messaging";

const firebaseConfig = {
  apiKey: "YOUR-API-KEY",
  authDomain: "YOUR-PROJECT.firebaseapp.com",
  projectId: "YOUR-PROJECT-ID",
  messagingSenderId: "YOUR-SENDER-ID",
  appId: "YOUR-APP-ID"
};

const app = initializeApp(firebaseConfig);
const messaging = getMessaging(app);

// Ask permission to show notifications
Notification.requestPermission().then(permission => {
  if (permission === 'granted') {
    getToken(messaging, { vapidKey: 'YOUR-VAPID-KEY' }).then(currentToken => {
      if (currentToken) {
        console.log('FCM Token:', currentToken);
        // Send this token to your server to store it
      } else {
        console.warn('No registration token available.');
      }
    });
  }
});

Step 4: Add a Service Worker

Create a file named firebase-messaging-sw.js in your public/ directory:

importScripts("https://www.gstatic.com/firebasejs/10.0.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/10.0.0/firebase-messaging.js");

firebase.initializeApp({
  apiKey: "YOUR-API-KEY",
  projectId: "YOUR-PROJECT-ID",
  messagingSenderId: "YOUR-SENDER-ID",
  appId: "YOUR-APP-ID"
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage(payload => {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
  };
  self.registration.showNotification(notificationTitle, notificationOptions);
});

Register it in your app:

navigator.serviceWorker.register('/firebase-messaging-sw.js')
  .then(registration => {
    console.log('Service Worker registered with scope:', registration.scope);
  });

Step 5: Sending a Message

You can now send a test notification using the Firebase Console or from your backend using an HTTP request:

POST https://fcm.googleapis.com/fcm/send
Headers:
  Authorization: key=YOUR_SERVER_KEY
  Content-Type: application/json

Body:
{
  "to": "USER_DEVICE_TOKEN",
  "notification": {
    "title": "Hello!",
    "body": "You’ve got a new message."
  }
}

Make sure to secure your server key and avoid exposing it in client-side code.


Best Practices

  • Store and manage tokens securely on your server.
  • Handle token refreshes to avoid sending messages to expired tokens.
  • Segment your audience using topics for more targeted messaging.
  • Respect user privacy and avoid over-notifying.

Conclusion

Push notifications are an excellent way to keep users informed and engaged. With Firebase Cloud Messaging, you can implement this feature in your web app efficiently, without the complexity of building your own messaging infrastructure. Whether you’re notifying users of new content, updates, or personal activity, push notifications can significantly enhance the user experience , when used thoughtfully.


Disclaimer

Article written with the help of AI.

Read the full Disclaimer HERE