0
0
Firebasecloud~5 mins

FCM setup in Firebase - Commands & Configuration

Choose your learning style9 modes available
Introduction
Firebase Cloud Messaging (FCM) helps you send notifications and messages to users' devices. It solves the problem of reaching users instantly with updates or alerts.
When you want to notify users about new messages in a chat app.
When you need to send alerts about app updates or promotions.
When you want to remind users about upcoming events or deadlines.
When you want to send silent data messages to update app content in the background.
When you want to engage users by sending personalized 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: "my-app.firebaseapp.com",
  projectId: "my-app",
  storageBucket: "my-app.appspot.com",
  messagingSenderId: "123456789012",
  appId: "1:123456789012:web:abcdef123456",
  measurementId: "G-ABCDEFGHJK"
});

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 for Firebase Cloud Messaging.

It imports Firebase scripts needed for messaging.

The firebase.initializeApp call sets up your Firebase project credentials.

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

Commands
Log in to your Firebase account to access your projects and use Firebase CLI commands.
Terminal
firebase login
Expected OutputExpected
✔ Success! Logged in as user@example.com
Initialize Firebase Cloud Messaging in your project. This sets up necessary files and configurations.
Terminal
firebase init messaging
Expected OutputExpected
=== Project Setup You're about to initialize Firebase Messaging in your project. ✔ Firebase Messaging setup complete.
Deploy your Firebase Cloud Messaging setup and any related cloud functions to Firebase servers.
Terminal
firebase deploy --only functions,messaging
Expected OutputExpected
=== Deploying to 'my-app'... ✔ functions: Finished running predeploy script. ✔ functions: All functions deployed successfully. ✔ messaging: Messaging configuration deployed. ✔ Deploy complete!
--only - Deploy only specified Firebase features to save time.
Send a test notification to a device using its FCM token to verify your setup works.
Terminal
firebase messaging:send --token eXampleToken1234567890 --notification-title "Hello" --notification-body "Welcome to our app!"
Expected OutputExpected
Message sent successfully to token eXampleToken1234567890
--token - Specify the device token to send the message to.
--notification-title - Set the title of the notification.
--notification-body - Set the body text of the notification.
Key Concept

If you remember nothing else from this pattern, remember: the service worker file handles background messages and must be correctly configured and deployed.

Common Mistakes
Not including the service worker file in the web app.
Without the service worker, background notifications won't show when the app is closed or in the background.
Always add and register the firebase-messaging-sw.js file in your web app root.
Using an incorrect or expired device token when sending test messages.
Messages will fail to deliver because the token is invalid or no longer active.
Always get the latest token from the client app before sending messages.
Not logging in to Firebase CLI before running commands.
Commands will fail due to lack of authentication.
Run 'firebase login' first to authenticate your CLI session.
Summary
Use 'firebase login' to authenticate your Firebase CLI session.
Initialize messaging with 'firebase init messaging' to set up necessary files.
Deploy your messaging setup using 'firebase deploy --only functions,messaging'.
Send test notifications with 'firebase messaging:send' using a valid device token.
The service worker file 'firebase-messaging-sw.js' handles background notifications.