DEV Community

Cover image for The Ultimate Guide To Firebase Cloud Messaging (FCM)
Emil Pearce for novu

Posted on • Originally published at novu.co

The Ultimate Guide To Firebase Cloud Messaging (FCM)

Learn the essentials of FCM, its implementation, FAQs, and best practices.

If you or your engineering team are using Firebase as the backend solution for your apps, FCM is one of the great options for cross-platform messaging solutions for push notifications.

This guide'll go through the complete how-to notify using FCM.


Why you should use Firebase Cloud Messaging (FCM) to drive user re-engagement

Push notifications are a powerful communication channel that's used by every successful app today. In many ways, it's the main interface for how users interact with your software.

These small, pop-up messages are sent to users devices by a mobile app and can be viewed from the device lock screen when an app isn't currently in use.

Unlike other communication channels like email, push notifications are designed to be viewed in real-time and often trigger immediate user re engagement.

Push notification

They can be used to convey reminders, updates, promotions, and more.


There are two types of push notifications:

  • Mobile push notification:

    Mobile push notifications are small, pop-up messages that can appear on a mobile device even when a user isn’t actively using an app.

  • Web push notifications:

    Web push notifications are small message alerts that are displayed on a visitor’s desktop, tablet, or mobile device when they have their web browser open.


How does Firebase FCM work?

How does Firebase FCM work

FCM relies on the following set of components that build, transport, and receive messages:

1. Message composition:

To create message requests, you can use the Notifications composer for a user-friendly interface. For more control and automation with all message types, you'll need to build requests in a trusted server environment supporting Firebase Admin SDK or FCM server protocol.

2. FCM backend:

This handles various tasks including receiving message requests, distributing messages via topics, and generating message metadata such as IDs.

3. Transport layer:

Messages are sent to devices through platform-specific transport layers:

  • Android Transport Layer (ATL) for Android devices with Google services.
  • Apple Push Notification service (APNs) for Apple devices.
  • Web push protocol for web apps.

4. FCM SDK on user devices:

The FCM SDK on the user's device manages how notifications are displayed or messages are handled based on the app's state (foreground/background) and any relevant app logic.


FCM push notifications message types

With FCM, you can send two types of messages to clients:

  • Notification messages are sometimes thought of as "display messages."

    These are handled by the FCM SDK automatically.

    • Contain a predefined set of user-visible keys.
    • Can include an optional data payload.
  • Data messages are handled by the client app. By contrast, contain only your user-defined custom key-value pairs.

The maximum payload for both message types is 4000 bytes, except when sending messages from the Firebase console, which enforces a 1000-character limit.


Use notification messages when you want the default FCM SDK to handle displaying a notification automatically when your app is running in the background.

Use data messages when you want to process the messages with your own client app code.

FCM can send a notification message with an optional data payload. In such cases, FCM handles displaying the notification payload, and the client app handles the data payload.


Notification messages

To programmatically send notification messages using the Admin SDK or the FCM protocols, set the notification key with the necessary predefined set of key-value options for the user-visible part of the notification message.

For example, here is a JSON-formatted notification message in an instant messaging (IM) app.

The user can expect to see a message with the title "Hello World" and the text "FCM is awesome!" on the device:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Hello World",
      "body":"FCM is awesome!"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Notification messages are delivered to the notification tray when the app is in the background. For apps in the foreground, send notification messages are handled by a callback function.

Basic notification template to use across all app package platforms:

JSON representation:

{
    "title":string,
    "body":string,
    "image":string
}
Enter fullscreen mode Exit fullscreen mode
Fields Type Description
title string The notification's title.
body string The notification's body text.
image string Contains the URL of an image that is going to be downloaded on the device and displayed in a notification.

JPEG, PNG, BMP have full support across platforms.

Animated GIF and video only work on iOS.

WebP and HEIF have varying levels of support across platforms and platform versions.

Android has 1MB image size limit.

Data messages

Set the appropriate key with your custom key-value pairs to reliably send messages with a data payload to the client app.

For example:

Here is a JSON-formatted message in the same IM app as above, where the information is encapsulated in the common data key and the client app is expected to interpret the content:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "data":{
      "Nick" : "John",
      "body" : "Hello World",
      "Room" : "FCM_Testers"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

The above example shows usage of the top-level, or common data field, which is interpreted by clients on all platforms that receive the message.

On each platform, the client app receives the data payload in a callback function.


Notification messages with optional data payload

Both programmatically or via the Firebase console, you can send notification messages that contain an optional payload of custom key-value pairs.

In the Notifications composer, use the Custom data fields in Advanced options.

FCM Notifications Composer

App behavior when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.

  • When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
  • When in the foreground, your app receives a message object with both payloads available.

Here is a JSON-formatted message containing both the notification key and the data key:

{
  "message":{
    "token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
    "notification":{
      "title":"Hello World",
      "body":"FCM is awesome!"
    },
    "data" : {
      "Nick" : "John",
      "Room" : "FCM_Testers"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Key features of the FCM push notification provider

Targeted distribution

Distribute messages to your client app in any of 3 ways:

  • To single devices.
  • To groups of devices.
  • To devices subscribed to topics.

3 ways to distribute messages

Delivery options

Controls message delivery behavior, including:

  • Collapsible message throttling (group similar notifications)
  • XMPP server throttling (limits messages to prevent server overload)
  • Maximum message rate to a single device
  • Topic message limit (controls messages sent to a topic)
  • Fanout throttling (limits messages sent to large device groups)

Priority

Supports setting message priority (normal or high) to influence delivery behavior.

Time to Live (TTL)

Enables setting message expiration times to ensure messages are not delivered after a specific timeframe.


Adding Push Notification Channel: Junior vs. Senior

When it comes to managing notifications across different channels, there's a big difference between how beginners and experts handle it. Let's break it down.


The Junior’s way

Beginners usually start with one notification channel, like Push or In-App, and will use Firebase Cloud Messaging (FCM). Later, once they need more channels, like SMS, Email, WhatsApp or Discord, they deal with each separately.

This creates a MESSY SYSTEM where different channels are connected in a patchwork way.

Here is Slack’s business logic for showing a notification:

Slack’s business logic for showing a notification

Keeping everything up-to-date becomes a headache because each channel needs individual attention.


The Senior’s way

Experts, on the other hand, use smarter methods. They do not spend their precious time on developing something from scratch, or lose energy on debugging and maintaining infrastructure.

It’s just like building your own database instead of using something that already works and performs, like Oracle, MySQL, PostgreSQL, or MongoDB.

They use notification infrastructure libraries, like Novu, that already have all the connections to various channels built-in, along with a ton of features, like Digest Engine, Delay Actions or Step Conditions.

With these libraries, setting up a solid notification system is quick and easy. All that needs to be done is just add the necessary parts and connect the channels they want, like FCM for push notifications or SendGrid for email.

The main difference here is in how efficient and scalable each approach is.

Beginners struggle with makeshift solutions and lots of maintenance. Professionals enjoy a smooth system that's easy to keep up-to-date and can grow as needed.

By using professional tools, you can communicate seamlessly across different channels, making it easier to reach your audience without dealing with the headaches of managing multiple systems.


The FCM Integration Flow For Mobile Devices

Sending push notifications via FCM usually involves the following steps

  1. Client App Registration: The mobile app installs on the device and registers itself with FCM during app launch. This registration generates a unique token for the device that identifies it for receiving messages.

  2. Token Retrieval: The mobile app retrieves the generated token and sends it to your app server. This token allows your server to target specific devices or groups of devices.

  3. Message Sending: Your app server prepares the message payload containing the information you want to deliver to the mobile app. This payload can include text, data, or a combination of both.

  4. FCM Connection: The app server connects to the FCM API using the Firebase Admin SDK or other libraries.

  5. Message Delivery: The app server sends the message payload and recipient information (tokens) to the FCM API.

  6. Routing and Delivery: FCM acts as a mediator, routing the message to the appropriate devices based on the provided tokens. FCM utilizes Google's infrastructure to ensure efficient and reliable message delivery.

  7. Wake-up Call (if needed): If the mobile app is in the background, FCM might send a wake-up call to activate it so it can receive the message.

  8. Message Received: The mobile app receives the message payload from FCM and parses the information.

  9. Action (Optional): The mobile app can then display a notification, play a sound, update its data, or perform any other actions based on the message content.

There might be additional considerations depending on your specific use case, such as error handling, data encryption, and advanced notification customization.


The FCM Integration Flow For Web Applications (Web Push)

NOTE:
FCM is primarily designed for mobile applications. However, there are workarounds to leverage FCM for basic push notification functionality in web applications.

Sending web push notifications via FCM usually involves the following steps

1. Web Push Protocol Integration:
Instead of FCM, you'll integrate with a Web Push Protocol (Web Push) service. Web Push is a browser-supported standard for sending notifications to web apps.

Providers like Firebase Push Notification service or other third-party solutions can be used.

2. User Subscription:
Within your web application, implement a mechanism for users to subscribe to notifications. This usually involves prompting the user for permission and storing a unique identifier (like a browser push token) for each subscribed user.

3. Message Preparation:
On your application server, prepare the notification payload containing the message and any data you want to deliver. This structure might differ slightly from FCM messages.

4. Push Service API Call:
Similar to FCM, your server communicates with the Web Push service API using its provided SDK or libraries. You'll send the message payload and the user's tokens to target specific subscribers.

5. Notification Delivery:
The Web Push service handles routing and delivers the notification to subscribed users' browsers. The browser displays the notification based on its notification permission settings.

Limitations

  • FCM vs Web Push: This approach utilizes a separate Web Push service instead of directly using FCM. Functionality might be more limited compared to FCM for mobile apps.
  • Browser Support: Web Push functionality relies on browser support, which might not be universal across all browsers and devices.
  • Background Updates: Unlike mobile apps, background updates or message delivery when the web app is closed might be limited.

Alternatives

Consider alternative approaches for web app notifications if these limitations are critical for your application:

  • Service Workers: Implement service workers for your web app to enable background functionality and potentially receive and display notifications even when the web app is closed (more complex setup).
  • Real-time Messaging: Utilize real-time messaging solutions or similar services for more interactive and data-driven communication with your web app.

Overall, while FCM isn't directly applicable to web apps. But with Novu it is possible (And easier).

The process involves setting up FCM and Novu, adding Firebase to your frontend project, and then integrating Novu into your backend to manage and trigger notifications. This setup allows you to send FCM push notifications to your web app users through Novu's unified API, leveraging Firebase's capabilities for web push.

We wrote this guide on How to send web push notifications with FCM and Novu.


How to send push notifications with FCM in a notification workflow

What Is A Notification Workflow?

Notification Workflows are represented as a set of steps, which are either function or channel steps.

Functions apply logic to your workflow run, like digest (batching to collapse) multiple notifications into single notification or delay action to pause the execution of a workflow for some duration.

Channel steps produce a notification that will be delivered via a configured ****channel (SMS, Email, Push etc.).

All steps can also have conditions to determine if and when they should run.

A workflow is the blueprint for the notifications (Or messages) that will be sent, holding the entire flow of messages sent to a subscriber (The End User / Recipient).

It includes the workflow's name and identifier, along with channel-tailored content, ensuring that all different channels are tied together under a single entity.

You need a notification workflow because it enables you to efficiently manage and customize how and when your messages are delivered to users across different channels.

Having a well-defined workflow ensures that your notifications are consistent, timely, and relevant to the recipient, enhancing the user experience and engagement with your product or service.

Additionally, it simplifies the notification management process, allowing non-technical team members to easily craft and update notification routing, content and designs, thereby fostering a more collaborative environment and quicker iterations on your notification strategy.

Novu Notification Workflow With FCM


To integrate FCM with Novu for sending push notifications, you typically follow these steps:

1. Setting up Firebase

This involves creating a Firebase project in the Firebase console, adding your app to the project, and configuring Firebase with your app's platform-specific details (Web, Android, iOS).

You can find more information in this documentation section.

Setting up Firebase

2. Setting up Novu

You need to add Firebase Cloud Messaging as a Push channel provider in the Novu Integrations Store.

You can find more information in this documentation section.

Novu integration store

3. Creating a Novu workflow

You can find more information in this documentation section.

Creating a workflow with Novu

4. Integrate FCM into your frontend (Client)

Here is how to add FCM instance into your frontend:

  1. This involves initializing Firebase in your app, requesting notification permissions from the user, and handling incoming messages.

  2. You'll also have to generate a token for each device using Firebase's getToken method, which is necessary to target notifications to individual devices.

We have dedicated guides for FCM integration:

5. Integrating Novu into your backend

Here is how to add Novu instance to your backend:

  1. This involves setting up the Novu SDK in your backend.

  2. Using Novu's API to create subscribers.

    cURL API request example:

    curl --location 'https://api.novu.co/v1/subscribers' \
      --header 'Content-Type: application/json' \
      --header 'Accept: application/json' \
      --header 'Authorization: ApiKey <NOVU_API_KEY>' \
      --data-raw '{
        "firstName": "Pawan",
        "lastName": "Jain",
        "email": "pawan.jain@domain.com",
        "phone": "+1234567890",
        "avatar": "avatar-url",
        "locale": "en-US",
        "data": {
          "isDeveloper": true,
          "customKey": "customValue"
          }
        }'
    
    
  3. Each subscriber can be associated with one or more device tokens (representing different devices or browsers).

Here is how to add device tokens to your subscriber:

```curl
curl --request PUT \
  --url https://api.novu.co/v1/subscribers/{subscriber_id}/credentials \
    --header 'Content-Type: application/json' \
  --header 'Authorization: ApiKey <YOUR_API_KEY>' \
  --data '{
      "credentials":{
    "deviceTokens": ["token1", "token2"]
        },
      "integrationIdentifier":"<Provider_Identifier>",
      "providerId":"fcm"
        }'
```
Enter fullscreen mode Exit fullscreen mode
  1. You then trigger notifications through Novu by specifying the workflow, subscriber ID, and notification content.

Here is how to trigger a workflow:

```curl
curl -X POST https://api.novu.co/v1/events/trigger \
  -H "Authorization: ApiKey <NOVU_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "<WORKFLOW_TRIGGER_IDENTIFIER>",
    "to": {
      "subscriberId": "<UNIQUE_SUBSCRIBER_IDENTIFIER>",
      "email": "john@doemail.com",
      "firstName": "John",
      "lastName": "Doe"
    },
    "payload": {
      "name": "Hello World",
      "organization": {
        "logo": "https://happycorp.com/logo.png"
      }
    }
  }'

```
Enter fullscreen mode Exit fullscreen mode

We have great quickstart guides and SDKs to help you get started.

With everything set up, you can send notifications from your backend by invoking the Novu API with the appropriate parameters. Novu will then use the FCM service to deliver the Push notifications to the targeted devices.


Why is relying solely on a push notification channel limiting?

  1. Opt-in requirement:

Push notifications require users to opt-in. If users don't opt-in or disable notifications later, they won't receive any communications through this channel.

  1. Device dependency:

Push notifications are device-specific. If the device is off or disconnected from the internet, the notification won't be delivered until the device is back online.

  1. Channel preferences:

Users have different preferences for receiving notifications. Some might prefer emails or SMS messages over push notifications. Novu supports channel preferences at the workflow, subscriber, and global levels, allowing for a more tailored communication strategy that can respect user preferences.

  1. Critical information delivery:

For critical notifications (e.g., account verification, password reset), relying on a single channel like push notifications can be risky. If the push notification is missed or not received, the user might miss essential information.

Novu allows marking certain workflows as critical, ensuring that these important notifications are not unsubscribed from, but it's still beneficial to notify through multiple channels.

  1. User engagement:

Different channels have different engagement rates. Push notifications might be effective for instant updates, but sending a new email or SMS might be better for more detailed information or for users who are not as active on their devices.

Considering these factors, it's advantageous to use a multi-channel approach for notifications to ensure higher delivery rates, cater to user preferences, and ensure critical information is reliably delivered.


FAQs

What is the difference between Firebase Cloud Messaging and Firebase Messaging?

There isn't actually a difference between Firebase Cloud Messaging (FCM) and Firebase Messaging.

  • Firebase Messaging is an older term that used to refer to the service.
  • Firebase Cloud Messaging (FCM) is the current, more specific name.

What are the two types of messages in Firebase cloud messaging?

Firebase Cloud Messaging (FCM) offers two main types of messages:

  1. Notification messages: These messages are designed to be displayed directly to the user. They typically contain a title, message body, and icon, and appear on the user's device even if the app is in the background. The FCM SDK on the device handles the notification automatically.

  2. Data messages: In contrast to notification messages, data messages don't have a predefined format and are delivered silently to the app. The app itself is responsible for interpreting and handling the data payload according to your app's logic. This gives you more flexibility to send any kind of information you need to your app.


How do I connect to FCM?

Connecting to FCM involves registering your app and setting up the Firebase SDK.

The specific steps depend on the platform you're developing for (Android, Web, etc.).

Here's a general overview:

  1. Register your app in Firebase:

    • Go to the Firebase console and create a project or select an existing one.
    • Enable the Firebase Cloud Messaging service for your project.
  2. Set up the Firebase SDK:

    • Download the Firebase SDK for your target platform (Android, iOS, Web) and integrate it into your app project.
    • Follow the platform-specific instructions to configure the SDK with your project details.
  3. Request notification permissions:

    You need to request notification permission at runtime from the user.

  4. Obtain a registration token:

    • The FCM SDK generates a unique registration token for your app instance.
    • You can use this token to identify your app and send targeted messages from your server.

Here are some resources that provide detailed instructions for different platforms:

These resources also cover additional steps like configuring Web Credentials and handling token updates.


What is FCM diagnosis?

FCM diagnosis refers to the process of troubleshooting message delivery issues within the FCM system. This is typically done for mobile apps that utilize FCM for sending messages.

FCM provides diagnostic tools to check delivery status and identify any problems that might be preventing messages from reaching the target devices.


How do I send notifications to all users with FCM?

Firebase Cloud Messaging (FCM) doesn't directly support sending notifications to absolutely all users because storing and managing individual registration tokens for every user wouldn't be scalable.

However, there are two common approaches to achieve a broadcast-like notification for a large user base:

  1. Topic Messaging: This method involves creating a topic on the FCM server and then asking all your users to subscribe to that topic within your app.

Once subscribed, any message you send to that topic will be delivered to all subscribed devices.

This is a good approach if you want to send general announcements or messages relevant to all users.

  1. Condition Messages: This approach is a bit more advanced and lets you target users based on a specific condition.

You can use the condition field when sending a message to FCM and specify a logical expression that evaluates to true for the targeted devices.

While not ideal for sending to all users exactly, it can be useful for reaching a very broad segment defined by a certain criteria.

For example, the condition could be 'all' in topics to target any devices subscribed to any topic.


Why use FCM notification instead of APNS?

You actually don't use FCM notification instead of APNS (Apple Push Notification Service). FCM actually works in conjunction with APNS for iOS devices. Here's a breakdown:

  • FCM (Firebase Cloud Messaging): This is a cross-platform messaging service from Google that lets you send notification messages and data messages to your app users on Android, iOS, and even web apps. It acts as a central hub for sending messages.

  • APNS (Apple Push Notification Service): This is Apple's proprietary service specifically for sending notifications to iOS devices. FCM relies on APNS to deliver messages to iPhones and iPads.

FCM acts as a middle layer that simplifies sending notifications across platforms while still utilizing APNS for iOS devices in the background.


How to get FCM device token?

The process of acquiring a Firebase Cloud Messaging (FCM) device token differs slightly depending on the platform you're developing for.

Here's a breakdown for Android and iOS:

Android:

  1. Add Firebase to your project: Integrate the Firebase SDK with your Android project following the official documentation.

  2. Request token in your app: Within your app, you can use the FirebaseInstanceId class to request the FCM device token.

Here's a common approach:

```java
FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
    @Override
    public void onSuccess(InstanceIdResult instanceIdResult) {
        String token = instanceIdResult.getToken();
        // Send the token to your server for further processing
    }
});
```
Enter fullscreen mode Exit fullscreen mode

iOS:

  1. CocoaPods or manual integration: Integrate the Firebase SDK with your iOS project using either CocoaPods or manual linking.

  2. Request permission and token: In your iOS app, request permission from the user to receive notifications and then fetch the FCM token.

Here's a simplified example:

```swift
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
    if granted {
        Messaging.messaging().token { token, error in
            if let error = error {
                print("Error getting FCM token: \(error)")
            } else if let token = token {
                print("FCM token: \(token)")
                // Send the token to your server for further processing
            }
        }
    } else {
        // Permission not granted
    }
}
```
Enter fullscreen mode Exit fullscreen mode

General Best Practices:

  • It's recommended to retrieve the FCM token on app startup and whenever it changes.
  • Send the FCM token to your server for secure storage and association with the specific user/device.
  • Implement a mechanism to handle situations where the token retrieval fails or becomes invalid.

Top comments (5)

Collapse
 
sumitsaurabh927 profile image
Sumit Saurabh

Anyone looking to integrate notifications in their apps has got to take a look here.

This is like a Swiss army knife for all things notifications.

Especially the cross-platform abilities.

Very thoroughly written piece! 🚀

Collapse
 
jainpawan21 profile image
Pawan Jain

@empe

If I have Android and iOS applications both, in that case also I consider FCM only or should look into other push providers like APNS, etc?

Collapse
 
empe profile image
Emil Pearce • Edited

Considering the scenario where you're managing both Android and iOS applications, opting for FCM is truly worth your consideration.

The main reasons for that are:

  • Cross-platform support: FCM seamlessly caters to both Android and iOS devices, sparing you the hassle of juggling separate push notification services for each platform.

  • You'll only need to acquaint yourself with one API for both platforms, saving precious time and resources along the way.

  • FCM presents a unified dashboard, allowing you to effortlessly oversee and track all your push notification campaigns across Android and iOS.

While APNS (Apple Push Notification service) is an option for iOS specifically, FCM integrates with APNS behind the scenes. This means you can leverage the combined functionalities of both platforms without directly dealing with APNS complexities.

Collapse
 
jainpawan21 profile image
Pawan Jain

Thanks, Emil 🙏🏻

Collapse
 
unicodeveloper profile image
Prosper Otemuyiwa

Amazing article about FCM @empe