0
0
Firebasecloud~5 mins

Notification handling in foreground in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When your app is open and running, it needs to show notifications differently than when it is closed. Handling notifications in the foreground means your app can decide how to show alerts or messages while the user is actively using it.
When you want to show a custom alert or message inside the app while the user is using it.
When you want to update the app's screen immediately after receiving a notification.
When you want to prevent the default system notification from showing while the app is open.
When you want to log or track notifications received during active app use.
When you want to play a sound or vibrate the device only when the app is in the foreground.
Config File - firebase-messaging-sw.js
firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/9.22.1/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/9.22.1/firebase-messaging-compat.js');

firebase.initializeApp({
  apiKey: "AIzaSyExampleKey1234567890",
  authDomain: "example-app.firebaseapp.com",
  projectId: "example-app",
  storageBucket: "example-app.appspot.com",
  messagingSenderId: "1234567890",
  appId: "1:1234567890:web:abcdef123456"
});

const messaging = firebase.messaging();

messaging.onBackgroundMessage(function(payload) {
  console.log('[firebase-messaging-sw.js] Received background message ', payload);
  const notificationTitle = payload.notification.title;
  const notificationOptions = {
    body: payload.notification.body,
    icon: '/firebase-logo.png'
  };

  self.registration.showNotification(notificationTitle, notificationOptions);
});

This file is the service worker that handles background notifications when the app is closed or in the background.

It initializes Firebase with your app's config and listens for background messages to show system notifications.

Foreground notifications are handled inside the app code, not here.

Commands
Install the Firebase JavaScript SDK version 9.22.1 to use Firebase services including messaging.
Terminal
npm install firebase@9.22.1
Expected OutputExpected
added 1 package, and audited 2 packages in 1s found 0 vulnerabilities
Check the installed Firebase SDK version to confirm the correct version is installed.
Terminal
node -e "console.log(require('firebase/app').SDK_VERSION)"
Expected OutputExpected
9.22.1
Deploy Firebase Cloud Messaging and related functions to enable notification handling in your app.
Terminal
firebase deploy --only functions,messaging
Expected OutputExpected
=== Deploying to 'example-app'... ✔ functions: Finished running predeploy script. ✔ functions: All functions deployed successfully! ✔ hosting: Hosting files deployed successfully ✔ messaging: Messaging deployed successfully Project Console: https://console.firebase.google.com/project/example-app/overview Deployment complete!
--only - Deploy only specified Firebase services to save time and avoid deploying unrelated parts.
Run your app locally to test notification handling in the foreground using Firebase Messaging SDK.
Terminal
node app.js
Expected OutputExpected
App started on http://localhost:3000 Listening for foreground notifications... Notification received: { title: 'Hello', body: 'Welcome to the app!' }
Key Concept

If you remember nothing else from this pattern, remember: foreground notifications require your app to listen and handle messages directly to control how alerts appear while the app is open.

Common Mistakes
Relying only on the service worker to show notifications when the app is open.
Service workers handle background notifications, so foreground messages won't show unless handled in app code.
Use Firebase Messaging's onMessage listener inside your app to handle notifications when the app is active.
Not initializing Firebase Messaging properly in the app before listening for messages.
Without proper initialization, the app cannot receive or handle messages correctly.
Initialize Firebase with your config and create a messaging instance before setting up message listeners.
Ignoring user permission requests for notifications.
Without permission, the app cannot receive or display notifications.
Always request and check notification permission before subscribing to messages.
Summary
Install Firebase SDK and initialize it with your app's configuration.
Use a service worker file to handle background notifications when the app is closed.
Inside your app, listen for foreground messages using Firebase Messaging's onMessage method to show custom alerts.
Deploy Firebase messaging services and test your app to confirm notifications appear correctly in foreground and background.