📖 Scenario: You are building a mobile app that needs to receive notifications even when the app is not open. This means the app must handle notifications in the background to alert users about important updates.
🎯 Goal: Create a Firebase Cloud Messaging (FCM) service worker script that handles notifications when the app is in the background. You will set up the initial service worker, configure notification options, implement the background message handler, and finalize the notification display.
📋 What You'll Learn
Create a service worker file named firebase-messaging-sw.js.
Initialize Firebase messaging in the service worker.
Add a configuration variable for notification title.
Implement the background message handler to show notifications.
Complete the notification display with icon and click action.
💡 Why This Matters
🌍 Real World
Mobile apps often need to notify users about updates even when the app is closed. Handling notifications in the background ensures users stay informed.
💼 Career
Understanding background notification handling is essential for mobile app developers and cloud engineers working with Firebase Cloud Messaging.
Progress0 / 4 steps
1
Create the Firebase messaging service worker
Create a file named firebase-messaging-sw.js and write the line importScripts('https://www.gstatic.com/firebasejs/9.22.1/firebase-app-compat.js'); to import Firebase app scripts.
Firebase
Hint
This line imports Firebase app scripts needed for messaging in the service worker.
2
Add Firebase messaging import and initialize app
In firebase-messaging-sw.js, add the line importScripts('https://www.gstatic.com/firebasejs/9.22.1/firebase-messaging-compat.js'); to import messaging scripts. Then initialize Firebase app with firebase.initializeApp({messagingSenderId: '1234567890'});.
Firebase
Hint
Import messaging scripts and initialize Firebase with your sender ID.
3
Implement background message handler with notification title
Create a constant notificationTitle with value 'Background Notification'. Then get messaging instance with const messaging = firebase.messaging();. Use messaging.onBackgroundMessage with a callback that receives payload and calls self.registration.showNotification(notificationTitle, {body: payload.data.body});.
Firebase
Hint
Set notification title, get messaging instance, and handle background messages to show notifications.
4
Complete notification with icon and click action
In the showNotification call, add an icon property with value '/firebase-logo.png' and a data property containing click_action with value 'https://www.example.com' inside the options object.
Firebase
Hint
Add icon and click action URL to the notification options for better user experience.
Practice
(1/5)
1. What is the main purpose of using onBackgroundMessage in Firebase Cloud Messaging?
easy
A. To authenticate users before sending notifications
B. To send messages from the client to the server
C. To handle notifications when the app is not open or in the background
D. To delete old notifications from the device
Solution
Step 1: Understand the role of onBackgroundMessage
This function is designed to catch messages when the app is not active or open.
Step 2: Compare with other options
Sending messages, authentication, or deleting notifications are unrelated to background message handling.
Final Answer:
To handle notifications when the app is not open or in the background -> Option C
Quick Check:
Background message handling = To handle notifications when the app is not open or in the background [OK]
Hint: Remember: background means app closed or hidden [OK]
Common Mistakes:
Confusing sending messages with receiving them
Thinking it manages user authentication
Assuming it deletes notifications automatically
2. Which of the following is the correct way to import and use onBackgroundMessage in a Firebase service worker?
easy
A. import { onBackgroundMessage } from 'firebase/messaging/sw'; onBackgroundMessage(handler);
B. import { onBackgroundMessage } from 'firebase/messaging/sw'; onBackgroundMessage(messaging, handler);
C. import { onBackgroundMessage } from 'firebase/messaging'; messaging.onBackgroundMessage(handler);
D. import { onBackgroundMessage } from 'firebase/messaging'; onBackgroundMessage(messaging, handler);
Solution
Step 1: Identify correct import path
The correct import for service worker usage is from 'firebase/messaging/sw'.
Step 2: Use correct function signature
onBackgroundMessage requires only the handler function as argument (no messaging instance needed).
Final Answer:
import { onBackgroundMessage } from 'firebase/messaging/sw'; onBackgroundMessage(handler); -> Option A
Quick Check:
Correct import and call signature = import { onBackgroundMessage } from 'firebase/messaging/sw'; onBackgroundMessage(handler); [OK]
Hint: Remember: import from 'firebase/messaging/sw' and pass handler only [OK]
Common Mistakes:
Importing from wrong path like 'firebase/messaging'
Passing messaging instance to onBackgroundMessage
Using messaging.onBackgroundMessage(handler)
3. Given this service worker code snippet, what will happen when a background message arrives?
A. Using self.registration.showNotification instead of Notification.show
B. Wrong import path for onBackgroundMessage ('firebase/messaging' instead of 'firebase/messaging/sw')
C. Not importing messaging from Firebase
D. Payload does not contain notification object
Solution
Step 1: Check onBackgroundMessage usage
The import path is wrong for service worker; must be from 'firebase/messaging/sw'.
Step 2: Verify notification method and imports
self.registration.showNotification is correct and messaging is imported but not needed.
Final Answer:
Wrong import path for onBackgroundMessage ('firebase/messaging' instead of 'firebase/messaging/sw') -> Option B
Quick Check:
Service worker import path = Wrong import path for onBackgroundMessage ('firebase/messaging' instead of 'firebase/messaging/sw') [OK]
Hint: Remember: import from 'firebase/messaging/sw' [OK]
Common Mistakes:
Using wrong import path for onBackgroundMessage
Confusing notification API names
Assuming payload structure is always wrong
5. You want to ensure your Firebase app shows a notification with a custom icon and vibrates when a background message arrives. Which code snippet correctly adds these features inside onBackgroundMessage?