Table of Contents

Introduction

Push notifications are a powerful tool to engage users by delivering timely updates directly to their devices. Firebase Cloud Messaging (FCM) is a free service provided by Google that enables developers to send notifications and messages to Android, iOS, and web applications. In this blog, we’ll dive into the key aspects of Firebase push notifications, how they work, and the steps involved in setting them up for your Flutter application.

What are Push Notifications?

Push notifications are short messages sent from a server to a user’s device. These notifications appear as pop-ups on mobile or web devices even when the user isn’t actively using the app. They can be used to:

  • Alert users about new updates
  • Remind users of upcoming events
  • Promote sales or offers
  • Encourage users to re-engage with the app

In this blog, we will be using the following services:

  • Firebase Messaging: For sending push notifications.
  • Firebase Cloud Functions with Node.js (JavaScript): For handling server-side logic.
  • Firebase Cloud Firestore: For managing and storing data.
  • Google Authentication: For generating authentication tokens.

How Firebase Push Notifications Work

Firebase Cloud Messaging (FCM) is at the core of push notifications. Here’s a step-by-step breakdown of the process:

Source: FCM

1. Client App Registration

When a user installs and opens an app integrated with FCM, the app automatically registers with Firebase and requests an FCM token. This token uniquely identifies the device and is required to target specific users.

First, add the required dependencies in pubspec.yaml:

In your main.dart, initialise Firebase and obtain the FCM token: 

2. Token Management 

To manage FCM tokens efficiently, especially since tokens can change over time (e.g., due to app reinstallations or user actions), you must ensure that your system can handle token updates and refreshes. Firebase provides a listener to detect when an FCM token changes. You also need to handle both device-specific tokens and topic-based subscriptions to ensure notifications are sent accurately. 

Handling Token Refresh (Including Topic-based Subscription) 

In this section, we’ll show how to: 

  1. Handle token refresh to update your backend with the new FCM token. 
  1. Automatically subscribe the user to relevant topics based on the new token. 

Code for Handling Token Refresh: 

Subscribe to a Topic

For sending push notifications we need to send create a server in this example, i am creating a firebase cloud functions which runs on nodeJS 20 runtime and using javascript for coding

3. Setuping Firebase Cloud Functions 

Set Up Firebase Admin SDK and Create a Service Account 

  1. Go to the Firebase Console: 
  • Navigate to the Firebase Console. 
  • Select your project. 
  1. Generate a Service Account Key: 
  • On the left-hand menu, click on Project Settings (gear icon). 
  • Go to the Service Accounts tab. 
  • Click on the Generate New Private Key button. 
  • A file with the name serviceAccountKey.json will be downloaded. This is your Firebase service account file. 
  1. Add serviceAccountKey.json to Your Project: 

Move the downloaded serviceAccountKey.json file to the root of your Cloud Functions project (next to index.js and package.json). 

Create utils/auth.js for Google Auth 

This file will handle Google authentication for accessing the Firebase Cloud Messaging API. 

Create utils/notification.js for Sending Notifications 

This file will be responsible for sending notifications using Firebase Cloud Messaging

Update index.js to Use Shared Code 

Now, your index.js can remain clean and use the shared utility functions. 

Step 4: Testing Your NodeJS Code 

Deploy the function: 

Once function deployed you will get API Endpoint that you can get from firebase cloud function dashboard on firebase. 

Test the function by sending an HTTP POST request with a payload: 

You can use Postman or curl to send the request. 

4. Message Delivery 

Once the message is sent, Firebase handles the delivery to the user’s device. FCM takes care of queuing the message if the device is offline and will deliver it once the device is back online. 

  • If the device is online, the message is delivered instantly. 
  • If the device is offline, FCM stores the message temporarily (for up to 4 weeks) and delivers it once the device reconnects to the internet. 

You can also specify message priorities to control how quickly messages should be delivered. 

5. User Interaction 

When the notification reaches the device, it can be displayed in different ways, depending on whether the app is in the foreground, background, or closed. 

Handling Notifications in the App (Flutter): 

  1. Foreground Notifications: When your app is open and running, notifications are handled by Firebase Messaging’s onMessage stream. 

2. Background Notifications: If your app is in the background or closed, the notification will appear in the device’s notification tray by default. 
You can customise the behaviour when the user taps the notification by handling the notification in onMessageOpenedApp. 

3. Handling Data Messages: Data messages are received in the background and foreground, allowing you to perform actions or update the UI without displaying a notification. 

6. Unsubscribing from Firebase Cloud Messaging (FCM) Topics 

Unsubscribing from topics in FCM allows users to stop receiving notifications for specific categories. Here’s a brief overview of how to implement it: 

1. Unsubscribing in Flutter 

To unsubscribe from a topic, use the FirebaseMessaging package: 

2. Unsubscribing in Node.js Backend 

In your Firebase Cloud Functions, you can unsubscribe a user from a topic like this: 

Unsubscribe Use Cases 

  • User Preferences: Allow users to control their notification settings. 
  • Account Changes: Unsubscribe users upon account deletion or preference updates. 

This way, you ensure users have control over the notifications they receive. 

Conclusion 

By integrating Firebase Cloud Messaging into your app, you can send real-time push notifications and data messages, driving user engagement. Firebase takes care of the complexities, such as token management and offline message queuing, while giving you full control over when, how, and to whom messages are sent.