0
0
Firebasecloud~7 mins

Notification handling in background in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
When your app is not open or running in the background, it still needs to receive and show notifications. This concept helps your app handle notifications even when users are not actively using it.
When you want to alert users about new messages even if the app is closed.
When you need to update app content silently in the background.
When you want to show reminders or alerts without opening the app.
When your app needs to react to notifications while running in the background.
When you want to improve user engagement by timely notifications.
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: "123456789012",
  appId: "1:123456789012: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 a service worker script that runs in the background.

It initializes Firebase with your app's config.

The onBackgroundMessage function listens for messages when the app is in the background and shows notifications.

The notification includes a title, body, and icon.

Commands
Deploys your service worker file and other hosting files to Firebase so the background notifications can work.
Terminal
firebase deploy --only hosting
Expected OutputExpected
=== Deploying to 'example-app'... i deploying hosting ✔ hosting: example-app ✔ Deploy complete! Project Console: https://console.firebase.google.com/project/example-app/overview
--only hosting - Deploy only the hosting part, including the service worker.
Sends a test notification to a specific device token to verify background notification handling.
Terminal
firebase messaging:send --token eXampleDeviceToken123456 --notification-title "Hello" --notification-body "You have a new message"
Expected OutputExpected
Successfully sent message: projects/example-app/messages/1234567890123456789
--token - Specifies the device token to send the notification to.
--notification-title - Sets the notification title.
--notification-body - Sets the notification body text.
Opens a live preview URL to test your deployed service worker and background notifications.
Terminal
firebase hosting:channel:open live
Expected OutputExpected
✔ Hosting URL: https://live--example-app.web.app You can now view your site in the browser.
Key Concept

If you remember nothing else from this pattern, remember: the service worker script handles notifications when the app is not active.

Common Mistakes
Not registering the service worker file in the app's main code.
Without registration, the browser won't run the background script, so notifications won't appear.
Add code in your app to register 'firebase-messaging-sw.js' as a service worker.
Using incorrect Firebase config in the service worker.
Wrong config prevents Firebase from initializing, so messages won't be received.
Copy the exact Firebase config from your Firebase console into the service worker.
Sending notifications without the notification payload.
Without notification fields, background messages may not show visible alerts.
Always include 'notification' with 'title' and 'body' in your message payload.
Summary
Create a service worker file 'firebase-messaging-sw.js' to handle background notifications.
Deploy the service worker using 'firebase deploy --only hosting'.
Send test notifications using Firebase CLI to verify background handling.
Remember to register the service worker in your app for it to work.