Integrating Firebase Cloud Messaging Where Supported in React Native
Course: React Native Training
Topic: Integrating Firebase Cloud Messaging Where Supported
Course Link: React Native Training at JustAcademy
Demo Link: Register for a Course Demo
JustAcademy Website: Visit JustAcademy
1. Introduction to Firebase Cloud Messaging
Firebase Cloud Messaging (FCM) is a messaging service that allows applications to send notifications and data messages to supported devices. In React Native applications, FCM can be used to deliver chat messages, order updates, reminders, announcements, and other server-generated events.
FCM connects a backend system with mobile devices through platform messaging infrastructure. Developers can use it to send messages when an important event occurs, even when the application is not currently open, subject to operating-system permissions, delivery conditions, and background execution restrictions.
React Native developers commonly integrate FCM using React Native Firebase Messaging or Expo Notifications, depending on the project architecture and requirements.
1.1 What Is Firebase Cloud Messaging?
Firebase Cloud Messaging is a cross-platform messaging service provided by Google. It supports sending messages to Android applications and can also be used with iOS applications through Apple Push Notification service (APNs).
FCM allows a backend server or trusted sending environment to deliver messages to registered application instances. The application can then display a notification, update relevant data, or respond to a user interaction according to the message type and platform behavior.
1.2 Why Use FCM in React Native?
- Deliver important updates from a backend server.
- Notify users about new messages and mentions.
- Send order, booking, and delivery status updates.
- Inform users about account activity and security events.
- Support notification-driven navigation to specific screens.
- Integrate push messaging with Firebase services and backend workflows.
- Use a shared messaging architecture for Android and supported iOS applications.
1.3 Learning Objectives
After completing this topic, learners should be able to:
- Explain the architecture and purpose of FCM.
- Understand the difference between notification messages and data messages.
- Create and configure a Firebase project.
- Install React Native Firebase Messaging.
- Configure Android and iOS platform requirements.
- Request notification permission where required.
- Register devices and manage messaging tokens.
- Receive messages in the foreground and handle background processing where supported.
- Navigate to the appropriate screen when a notification is tapped.
- Test notification delivery and troubleshoot common integration problems.
2. Understanding FCM Architecture
FCM uses a messaging infrastructure to deliver messages from a trusted sending environment to registered application instances.
2.1 Main Components
- React Native application: Requests permission, registers for messaging, obtains tokens, and processes incoming messages.
- Firebase project: Stores project configuration and provides access to Firebase services.
- FCM registration token: Identifies an application instance as a destination for messages.
- Backend server: Determines when to send messages and which users or devices should receive them.
- FCM service: Routes messages to the target application instance.
- Android notification system or APNs: Helps deliver and present notifications according to platform rules.
- Application navigation: Opens the relevant screen when a user interacts with a notification.
2.2 How FCM Works
- The developer creates a Firebase project.
- The Android or iOS application is registered with the appropriate Firebase configuration.
- The application integrates the required messaging library.
- The application obtains an FCM registration token when registration succeeds.
- The token is securely associated with the user or device in the backend when necessary.
- An event occurs, such as a new message or order status change.
- The backend sends a message using the FCM HTTP v1 API or Firebase Admin SDK.
- FCM attempts to deliver the message to the registered application instance.
- The operating system or application handles the message according to its payload, state, and platform configuration.
- The user may tap the notification to open the application or view relevant information.
2.3 Architecture Diagram
React Native Application
|
| Register and obtain FCM token
v
Firebase Cloud Messaging
|
| Token registration sent securely
v
Backend Server
|
| Business event occurs
v
Firebase Admin SDK / FCM HTTP v1 API
|
v
Firebase Cloud Messaging
|
+-------------------------+
| |
v v
Android Device iOS Device
| |
v v
Android Notification Apple Push Notification
System Service (APNs)
| |
+------------+------------+
|
v
React Native Application
For iOS, FCM uses APNs to deliver remote notifications. The application requires the appropriate Apple push notification credentials and platform configuration.
3. Supported Platforms and Integration Choices
FCM integration depends on the application framework, platform, build configuration, and required notification features. Choose an approach that fits the project's architecture rather than mixing multiple notification systems unnecessarily.
| Environment |
Integration Approach |
Important Consideration |
| React Native CLI for Android |
React Native Firebase Messaging or a suitable native messaging integration |
Configure Firebase Android files, Gradle, permissions, and notification behavior. |
| React Native CLI for iOS |
React Native Firebase Messaging with APNs configuration |
Configure Apple capabilities, signing, and push credentials. |
| Expo application using Expo Push Service |
Expo Notifications |
Expo handles much of the push delivery integration, while platform credentials still need configuration. |
| Expo application using native FCM integration |
React Native Firebase Messaging in a development build |
Requires native code and cannot run in the standard Expo Go application. |
| Web application |
Firebase Web Messaging where supported |
Uses browser-specific configuration and service workers, not the same React Native mobile integration. |
Important: This topic focuses on native React Native mobile applications. A web implementation requires a different setup. Always verify current platform requirements before choosing a library.
4. Creating a Firebase Project
The first step is to create a Firebase project and register the mobile applications that will use FCM.
4.1 Open Firebase Console
- Open Firebase Console.
- Sign in with your Google account.
- Create a new project or select an existing project.
- Follow the setup steps shown in the console.
- Open the project dashboard.
- Register the Android and/or iOS application as required.
4.2 Register an Android Application
- Select the option to add an Android application.
- Enter the Android package name used by the React Native project.
- Optionally provide the application nickname and signing certificate fingerprints where required by your broader Firebase setup.
- Download the
google-services.json configuration file.
- Place the file in the location specified by the current React Native Firebase setup instructions, commonly the Android app module directory.
- Complete the required Gradle and native project configuration.
The Android package name must match the application ID configured in the native Android project. If the identifiers do not match, Firebase initialization or service configuration may fail.
4.3 Register an iOS Application
- Select the option to add an iOS application.
- Enter the iOS bundle identifier.
- Download the
GoogleService-Info.plist configuration file.
- Add the file to the iOS project using the correct project configuration.
- Configure the Apple Push Notification capability.
- Configure the required APNs credentials in Firebase.
- Build and test on a supported iOS device with the required signing configuration.
The bundle identifier must match the iOS application's configured bundle identifier. The Firebase configuration file alone is not sufficient to enable remote notifications on iOS.
5. Installing React Native Firebase Messaging
React Native Firebase provides native Firebase SDK integrations for React Native applications. Its messaging module exposes APIs for obtaining tokens, requesting permission, receiving messages, and handling notification interactions.
Official documentation: React Native Firebase Cloud Messaging Usage Guide.
5.1 Install the Core Firebase Module
For a compatible React Native CLI project, install the Firebase app module first:
npm install @react-native-firebase/app
5.2 Install the Messaging Module
npm install @react-native-firebase/messaging
For iOS projects, install the native CocoaPods dependencies after installing the packages:
cd ios
pod install
cd ..
Follow the current official installation instructions for the versions of React Native, Firebase, Android Gradle Plugin, Gradle, Kotlin, Xcode, and CocoaPods used by your project.
5.3 Rebuild the Native Application
Native Firebase modules require a native build. Restarting only the JavaScript development server does not compile a newly installed native dependency.
npx react-native run-android
For iOS, open the workspace in Xcode or use the project's supported iOS build command after completing native setup.
React Native Firebase requires custom native code. In Expo projects, use a development build and follow the Expo config plugin instructions; it cannot run in the standard Expo Go application.
6. Integrating FCM in an Expo Project
Expo projects have two main options for push notifications. Selecting the correct one is important because the configuration and token types differ.
6.1 Option A: Expo Notifications and Expo Push Service
Use this approach when you want Expo to manage much of the push delivery workflow. Expo Push Service routes messages through the relevant platform infrastructure, including FCM on Android and APNs on iOS.
npx expo install expo-notifications expo-constants
Configure the Expo application and push credentials according to the official guide:
Expo Push Notifications Overview
In this approach, the application normally obtains an Expo push token for use with Expo Push Service. This is different from a native FCM registration token.
6.2 Option B: Direct FCM Integration with React Native Firebase
Choose this approach when the application needs native Firebase Messaging integration or the backend sends messages directly through FCM.
- Install the React Native Firebase app module.
- Install the messaging module.
- Configure the native Firebase project files.
- Configure the required Android and iOS push notification settings.
- Build a development version of the application.
- Obtain a native FCM registration token.
- Register the token with the backend securely.
Do not assume that an Expo push token can be used directly as an FCM registration token. They identify destinations for different messaging workflows.
7. Requesting Notification Permission
Notification permission controls whether the application can display notifications under the platform's permission model. The permission requirements vary across Android and iOS versions.
7.1 Request Permission with React Native Firebase
import messaging from '@react-native-firebase/messaging';
import { Platform, PermissionsAndroid } from 'react-native';
export async function requestMessagingPermission() {
if (Platform.OS === 'ios') {
const status = await messaging().requestPermission();
return (
status === messaging.AuthorizationStatus.AUTHORIZED ||
status === messaging.AuthorizationStatus.PROVISIONAL
);
}
if (
Platform.OS === 'android' &&
Number(Platform.Version) >= 33
) {
const status = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS
);
return status === PermissionsAndroid.RESULTS.GRANTED;
}
return true;
}
This example handles common permission cases for iOS and Android 13 or later. Production applications should also account for permission status changes, device-specific restrictions, and the complete Android notification configuration.
7.2 Why Permission Timing Matters
- Explain the benefit of notifications before requesting permission.
- Ask at a point when the user understands the feature.
- Respect users who decline permission.
- Provide an in-app settings page to manage notification preferences.
- Avoid repeatedly prompting users who have already declined.
- Do not assume a valid FCM token means visible notifications are authorized.
8. Obtaining an FCM Registration Token
An FCM registration token identifies an application instance as a destination for messages. The application can obtain this token and send it to a trusted backend that needs to target the device.
8.1 Retrieve the Token
import messaging from '@react-native-firebase/messaging';
export async function getFcmToken() {
const token = await messaging().getToken();
return token;
}
Call this after Firebase has been configured. In applications where permission is needed before notification presentation, request permission at the appropriate point in the flow before proceeding with notification-specific setup.
8.2 Register the Token with a Backend
export async function registerDeviceToken(token, accessToken) {
const response = await fetch(
'https://api.example.com/devices/fcm-token',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`
},
body: JSON.stringify({
token,
platform: 'mobile'
})
}
);
if (!response.ok) {
throw new Error('Unable to register FCM token.');
}
return response.json();
}
This is an illustrative example. Replace the URL with your own backend endpoint and authenticate the request. The backend should associate the token with the correct user or installation and should not trust a client-provided user identity without validating authentication.
8.3 Handle Token Refresh
FCM tokens can change. An application should listen for token updates and synchronize the latest token with its backend.
import messaging from '@react-native-firebase/messaging';
export function listenForFcmTokenRefresh(syncToken) {
return messaging().onTokenRefresh(async token => {
try {
await syncToken(token);
} catch (error) {
console.error('FCM token synchronization failed.');
}
});
}
The syncToken function should securely update the backend registration. Remove the listener when it is no longer needed, and handle temporary network errors so token synchronization can be retried.
9. Receiving Messages in the Foreground
When an application is active, FCM messages can be received by a foreground listener. A foreground message does not necessarily create a visible system notification automatically, so the application may need to update its UI or display a local notification.
9.1 Listen for Foreground Messages
import messaging from '@react-native-firebase/messaging';
export function listenForForegroundMessages() {
return messaging().onMessage(async remoteMessage => {
console.log(
'Foreground message:',
remoteMessage.notification?.title
);
console.log(
'Message data:',
remoteMessage.data
);
});
}
Use the listener to update a message list, refresh an order status, or display suitable in-app feedback. If a visible system notification is required while the app is in the foreground, configure the notification presentation behavior or use an appropriate local notification library.
9.2 Register the Listener in a React Component
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import messaging from '@react-native-firebase/messaging';
export default function HomeScreen() {
useEffect(() => {
const unsubscribe = messaging().onMessage(
async remoteMessage => {
console.log(
'Received:',
remoteMessage.notification?.title
);
}
);
return unsubscribe;
}, []);
return (
<View>
<Text>Home Screen</Text>
</View>
);
}
Register listeners at an appropriate level of the application. If a listener is registered on every screen unnecessarily, the same message may be processed multiple times.
10. Handling Background Messages
Background message handling allows an application to process certain incoming messages while it is not active. The operating system places restrictions on background execution, and behavior differs between Android and iOS.
10.1 Register a Background Message Handler
For React Native Firebase, register the background handler outside the React component tree, typically in the application's entry file.
// index.js
import { AppRegistry } from 'react-native';
import messaging from '@react-native-firebase/messaging';
import App from './App';
import { name as appName } from './app.json';
messaging().setBackgroundMessageHandler(
async remoteMessage => {
console.log(
'Background message received:',
remoteMessage.messageId
);
// Process suitable background data here.
}
);
AppRegistry.registerComponent(appName, () => App);
The background handler must be registered early, outside the UI component lifecycle. Keep background work short and suitable for the platform's execution limits.
10.2 Background Handling Considerations
- Background execution is not guaranteed for every message.
- Data-only messages may require platform-specific priority and payload configuration.
- iOS may defer or omit background processing depending on system conditions.
- Do not rely on background messages to execute critical business transactions.
- Perform authoritative business logic on the backend.
- Use a local notification library when a data message needs to produce a visible notification.
11. Notification Messages and Data Messages
FCM supports different message payloads. Understanding the distinction is important because notification presentation and JavaScript callbacks can behave differently depending on the message type and application state.
11.1 Notification Message
A notification message contains a notification payload such as a title and body. When the app is in the background, the operating system commonly handles displaying it, subject to permissions and platform behavior.
{
"message": {
"token": "FCM_REGISTRATION_TOKEN",
"notification": {
"title": "Order Update",
"body": "Your order has been shipped."
}
}
}
11.2 Data Message
A data message contains key-value data intended for application processing. A data-only message does not automatically guarantee a visible notification. The application may need to process the data and display a notification using a suitable library.
{
"message": {
"token": "FCM_REGISTRATION_TOKEN",
"data": {
"type": "order_update",
"orderId": "ORDER_123",
"status": "shipped"
}
}
}
11.3 Notification and Data Combined
A combined message includes a visible notification payload and custom data that the application can use when handling the notification interaction.
{
"message": {
"token": "FCM_REGISTRATION_TOKEN",
"notification": {
"title": "Order Shipped",
"body": "Tap to view your order."
},
"data": {
"screen": "OrderDetails",
"orderId": "ORDER_123"
}
}
}
11.4 Comparison Table
| Feature |
Notification Message |
Data Message |
Combined Message |
| Contains title and body |
Yes, when configured |
Not automatically |
Yes, when configured |
| Custom application data |
Optional |
Yes |
Yes |
| Automatic visible presentation |
Common in background scenarios |
Not guaranteed |
Common in background scenarios |
| Application processing |
Depends on state and message handling |
Depends on platform and execution state |
Depends on state and user interaction |
| Typical use |
Simple announcement |
Application data update |
Notification with navigation data |
Message handling is platform- and state-dependent. Validate the expected behavior for the precise combination of payload, operating system, app state, and React Native Firebase version you use.
12. Handling Notification Taps
Notification taps should take users to the correct part of the application. For example, tapping an order notification should open the order details screen rather than always opening the home screen.
12.1 Handle Notifications Opened from the Background
import messaging from '@react-native-firebase/messaging';
export function listenForNotificationOpens(navigate) {
return messaging().onNotificationOpenedApp(
remoteMessage => {
const data = remoteMessage.data;
if (data?.screen === 'OrderDetails' && data?.orderId) {
navigate('OrderDetails', {
orderId: data.orderId
});
}
}
);
}
12.2 Handle Notifications That Launch the App
When a notification launches an application from a quit state, retrieve the initial notification and process its data after navigation is ready.
import messaging from '@react-native-firebase/messaging';
export async function handleInitialNotification(navigate) {
const remoteMessage =
await messaging().getInitialNotification();
if (!remoteMessage) {
return;
}
const data = remoteMessage.data;
if (data?.screen === 'OrderDetails' && data?.orderId) {
navigate('OrderDetails', {
orderId: data.orderId
});
}
}
In a complete application, coordinate this logic with navigation initialization so navigation does not run before the navigation container is ready.
12.3 Validate Notification Data
- Check that required fields exist.
- Validate identifiers and data types.
- Do not trust a payload as proof that the current user can access a resource.
- Verify authorization with the backend before showing protected information.
- Provide a safe fallback route for unsupported or invalid payloads.
13. Sending FCM Messages from a Backend
Remote notifications should generally be sent from a trusted backend using the Firebase Admin SDK or FCM HTTP v1 API. Privileged service-account credentials must never be embedded in the React Native application.
13.1 Install Firebase Admin SDK
For a Node.js backend, install the Firebase Admin package:
npm install firebase-admin
13.2 Initialize Firebase Admin
Configure the Admin SDK using a suitable server-side credential method. The following example assumes that the server environment has already been configured with secure Application Default Credentials.
const admin = require('firebase-admin');
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
Use a secure production credential strategy. Do not commit service-account private keys to source control or include them in mobile application bundles.
13.3 Send a Notification to a Device
async function sendOrderNotification(fcmToken) {
const message = {
token: fcmToken,
notification: {
title: 'Order Shipped',
body: 'Your order is on its way.'
},
data: {
screen: 'OrderDetails',
orderId: 'ORDER_123'
},
android: {
priority: 'high'
},
apns: {
payload: {
aps: {
sound: 'default'
}
}
}
};
const messageId = await admin.messaging().send(message);
return messageId;
}
This example demonstrates the general message structure. Use an actual registered FCM token, validate the intended recipient, and select priority settings according to the message's purpose. High priority should not be used indiscriminately.
13.4 Send a Notification to a Topic
FCM topics allow multiple subscribed application instances to receive the same message. They can be useful for public announcements or shared categories of updates.
async function sendAnnouncement() {
const message = {
topic: 'general_announcements',
notification: {
title: 'New Announcement',
body: 'A new update is available.'
}
};
return admin.messaging().send(message);
}
Topic subscriptions should be designed carefully. Do not use publicly subscribable topics as an authorization mechanism for private user data or sensitive notifications.
14. Android-Specific FCM Configuration
Android applications require Firebase configuration and appropriate notification settings. The exact setup depends on the React Native version, Gradle configuration, Firebase SDK, and Android version.
14.1 Add Firebase Configuration
- Register the Android application in Firebase Console.
- Confirm the Android application ID matches the registered package name.
- Add the downloaded
google-services.json file in the correct native project location.
- Configure the Google Services Gradle plugin as required by the current setup guide.
- Rebuild the application after native changes.
14.2 Android 13 and Later Notification Permission
Android 13 and later introduce a runtime notification permission for many standard notifications. Request POST_NOTIFICATIONS at an appropriate point and handle denial gracefully.
<uses-permission
android:name="android.permission.POST_NOTIFICATIONS" />
Follow the React Native Firebase and Android documentation for the exact manifest and permission behavior. Some older Android versions do not use this same runtime permission model.
14.3 Notification Channels
Android 8.0 and later use notification channels to categorize notifications. Create suitable channels for messages, reminders, order updates, or other categories.
Channel settings are user-controlled. Changing channel importance in the application does not necessarily override an existing channel's user-selected settings.
15. iOS-Specific FCM Configuration
On iOS, FCM integrates with Apple Push Notification service. Firebase configuration alone does not complete the push notification setup.
15.1 Configure APNs
- Open the iOS project in Xcode.
- Configure the correct bundle identifier and signing team.
- Enable the Push Notifications capability.
- Configure the required background modes if the application's use case requires them.
- Create or obtain an APNs authentication key or another supported credential.
- Upload the required APNs credentials in Firebase Console.
- Ensure the application registers correctly for remote notifications.
- Build and test on an appropriate physical device.
15.2 Request iOS Notification Authorization
Use the messaging permission API and check the resulting authorization status. iOS may provide authorized, provisional, or denied outcomes depending on user choices and system settings.
import messaging from '@react-native-firebase/messaging';
export async function requestIosPermission() {
const status = await messaging().requestPermission();
const enabled =
status === messaging.AuthorizationStatus.AUTHORIZED ||
status === messaging.AuthorizationStatus.PROVISIONAL;
return enabled;
}
Provisional authorization may allow notifications to be delivered quietly, depending on the iOS notification model. Test actual presentation behavior on the target operating-system version.
16. Managing Tokens and User Sessions
Token management is essential for reliable push notification delivery. A token can change, become invalid, or become associated with a different user session if the application does not manage registration correctly.
16.1 Recommended Token Management Practices
- Store tokens securely on the backend.
- Associate tokens with the correct authenticated user or installation.
- Listen for token refresh events.
- Remove or deactivate stale tokens when they are no longer valid.
- Handle users who sign out or switch accounts.
- Prevent duplicate device registrations where possible.
- Do not expose tokens unnecessarily in logs or analytics.
- Use delivery errors to identify invalid registration tokens.
16.2 Example Sign-Out Cleanup
export async function unregisterDeviceFromBackend(
accessToken,
fcmToken
) {
const response = await fetch(
'https://api.example.com/devices/fcm-token',
{
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${accessToken}`
},
body: JSON.stringify({ token: fcmToken })
}
);
if (!response.ok) {
throw new Error('Failed to unregister device token.');
}
}
This is an example backend contract, not a built-in Firebase endpoint. Implement the matching endpoint on your server. The server should verify the authenticated user and ensure the token is removed only from the appropriate registration.
17. Security and Privacy Best Practices
Push notifications can carry sensitive information, so secure implementation is important.
- Protect server credentials: Keep Firebase Admin credentials on the backend.
- Authenticate token registration: Verify the user before associating a device token with an account.
- Validate message content: Prevent unauthorized users from triggering messages to other users.
- Minimize sensitive payload data: Avoid passwords, authentication secrets, payment information, and private records.
- Verify authorization after a tap: A notification payload must not grant access to a protected resource.
- Respect preferences: Apply user choices for optional notification categories.
- Limit topic exposure: Do not rely on topic names to protect private information.
- Monitor delivery errors: Remove invalid tokens and investigate unexpected sending patterns.
- Use appropriate message priorities: Follow platform policies and use high priority only when justified.
18. Troubleshooting Common FCM Problems
| Problem |
Possible Cause |
Solution |
| FCM token cannot be obtained |
Firebase initialization or native configuration is incomplete. |
Check Firebase files, package installation, and native build configuration. |
| Android push notifications do not arrive |
Incorrect project configuration, token, or sending credentials. |
Verify the Firebase project, token, and server configuration. |
| iOS notifications do not arrive |
APNs credentials, signing, or capabilities are incorrect. |
Review the Apple push setup and Firebase APNs configuration. |
| Notification permission is denied |
The user declined permission or disabled notifications. |
Respect the decision and explain how to enable notifications in settings. |
| Message received but no banner appears |
The app is foregrounded or presentation settings are incomplete. |
Configure foreground presentation or show an appropriate local notification. |
| Background handler does not run |
Unsupported message type, priority, app state, or platform restriction. |
Review background handler registration and message configuration. |
| Tap does not open the correct screen |
Missing payload data or navigation is not ready. |
Validate data fields and coordinate notification handling with navigation initialization. |
| Invalid registration token |
The token is stale or belongs to another project. |
Refresh token registration and remove invalid tokens. |
| Messages are duplicated |
Duplicate listeners, retry logic, or multiple sending paths. |
Review subscriptions, server retries, and message identifiers. |
| Expo project fails to use React Native Firebase |
Native modules are being used in Expo Go. |
Configure and build a supported development build. |
| Push works only on Android |
iOS APNs credentials or native configuration are missing. |
Complete and test the iOS push notification setup. |
19. Testing Firebase Cloud Messaging
Testing should cover message delivery, permissions, notification presentation, application lifecycle states, and navigation.
19.1 Testing Checklist
- Confirm the Firebase project and application identifiers are correct.
- Verify native Firebase configuration is included in the build.
- Check that a valid FCM token can be obtained.
- Confirm the token is registered with the backend.
- Send a test notification using a trusted sending environment.
- Test the application in the foreground.
- Test the application in the background.
- Test notification taps when the application is not running.
- Test the permission-denied scenario.
- Test token refresh and invalid token handling.
- Check notification channels on Android.
- Verify APNs configuration on iOS.
- Inspect backend responses and messaging service errors.
19.2 Firebase Console Testing
Firebase Console provides notification-related tools for supported testing workflows. For advanced data payloads, application-specific targeting, or production message sending, use the appropriate backend and FCM HTTP v1 or Admin SDK workflow.
Official guide: Firebase Cloud Messaging Documentation.
20. Practical Project: Real-Time Order Notifications
Build a React Native shopping application that sends push notifications when an order is confirmed, shipped, or delivered.
20.1 Project Requirements
- Configure a Firebase project.
- Register the Android application and optionally the iOS application.
- Install React Native Firebase Messaging.
- Request notification permission where required.
- Obtain and register an FCM token.
- Store the token securely in the backend.
- Send an FCM notification when an order status changes.
- Include the order identifier in the notification data.
- Handle foreground messages and notification interactions.
- Navigate to the order details screen when a notification is tapped.
- Handle invalid tokens and notification permission changes.
20.2 Suggested Project Structure
src/
components/
NotificationBanner.js
OrderCard.js
screens/
HomeScreen.js
OrderDetailsScreen.js
NotificationSettingsScreen.js
services/
fcmService.js
notificationNavigation.js
apiService.js
navigation/
AppNavigator.js
App.js
index.js
20.3 Development Steps
- Create the React Native application.
- Set up Firebase Console and register the mobile app.
- Install and configure React Native Firebase modules.
- Build the permission and token registration flow.
- Implement foreground and background message handlers.
- Implement backend message sending.
- Include safe navigation data in notifications.
- Connect notification taps to order details.
- Test on supported physical devices.
- Document the setup, credentials, and troubleshooting process.
21. Interview Questions and Answers
Q1. What is Firebase Cloud Messaging?
Answer: Firebase Cloud Messaging is a service that sends messages from a trusted sending environment to registered application instances on supported platforms.
Q2. What is React Native Firebase Messaging?
Answer: It is a React Native module that integrates native Firebase Cloud Messaging capabilities into Android and iOS applications.
Q3. What is an FCM registration token?
Answer: It identifies an application instance as a destination for FCM messages. The backend uses the token to address messages to the appropriate instance.
Q4. What is the difference between a notification message and a data message?
Answer: A notification message contains notification content for presentation, while a data message contains key-value data intended for application processing. Actual handling depends on platform and app state.
Q5. Why is APNs required for iOS?
Answer: Apple Push Notification service provides the underlying delivery infrastructure for remote notifications on Apple devices, including notifications sent through FCM.
Q6. What does onMessage do?
Answer: It registers a listener for messages received while the application is in the foreground.
Q7. What does setBackgroundMessageHandler do?
Answer: It registers a handler for supported background message processing. It must be configured outside the React component tree and must respect operating-system restrictions.
Q8. Why should tokens be refreshed?
Answer: FCM tokens can change. Updating the backend registration helps maintain a valid destination for push messages.
Q9. Can FCM display notifications when the application is closed?
Answer: Notification messages may be displayed when the application is not active, depending on platform configuration, permissions, delivery conditions, and message type. Background JavaScript execution is not guaranteed.
Q10. Can React Native Firebase run in Expo Go?
Answer: No. React Native Firebase requires native code that is not included in the standard Expo Go application. Use a supported development build for this integration.
Q11. Why should FCM sending happen on the backend?
Answer: The backend can securely authenticate requests, authorize recipients, and use privileged messaging credentials without exposing them in the mobile application.
Q12. What is a notification channel?
Answer: On supported Android versions, a notification channel groups notifications by category and lets users manage their behavior.
Q13. What is a notification payload used for?
Answer: It contains information intended for notification presentation, such as a title and body.
Q14. How can a notification open a specific screen?
Answer: Include validated navigation data in the payload, handle the user's notification response, and navigate when the application navigation system is ready.
Q15. What are common FCM integration issues?
Answer: Common issues include invalid tokens, missing Firebase configuration, incorrect APNs credentials, permission denial, unsupported background execution, and incomplete native builds.
22. Practice Exercises
- Create a Firebase project and register an Android application.
- Install React Native Firebase App and Messaging modules.
- Request notification permission on supported platforms.
- Retrieve an FCM registration token and display a safe diagnostic result.
- Register the token with a backend endpoint.
- Implement a foreground message listener.
- Register a background message handler in the entry file.
- Send a test notification from a trusted backend.
- Create a notification payload with custom navigation data.
- Handle notification taps when the app is in the background.
- Handle the initial notification when the app launches from a notification.
- Test token refresh and invalid token cleanup.
- Configure and test iOS APNs credentials where applicable.
- Document platform-specific notification limitations.
23. Quick Revision Notes
- FCM: Firebase Cloud Messaging, a push messaging service.
- React Native Firebase: Native Firebase integration for React Native applications.
- FCM token: Identifies an application instance as a messaging destination.
- Backend server: Sends authorized messages using the Admin SDK or FCM HTTP v1 API.
- APNs: Apple's push notification delivery infrastructure.
- Notification message: Contains notification presentation information.
- Data message: Contains key-value data for application processing.
- onMessage: Handles messages received in the foreground.
- setBackgroundMessageHandler: Handles supported background message processing.
- onNotificationOpenedApp: Handles a notification that opens the application from the background.
- getInitialNotification: Retrieves a notification that launched the application from a quit state.
- Token refresh: Keeps the backend registration synchronized.
- Expo Go: Does not include the native code required by React Native Firebase.
- Security: Keep privileged sending credentials on the backend.
- Testing: Verify permissions, delivery, foreground behavior, background handling, and notification navigation.
24. Conclusion
Firebase Cloud Messaging is an important capability for React Native applications that need to communicate server-generated events to users. Integrating FCM requires correct Firebase configuration, native platform setup, permission handling, token registration, message processing, and notification interaction handling.
Android and iOS share the overall messaging concept, but their setup and delivery behavior differ. Android uses Firebase messaging infrastructure with Android notification features, while iOS remote notifications are delivered through APNs. Expo projects may use Expo Push Service or a direct native integration depending on their requirements.
By following secure token management practices, testing application lifecycle states, validating notification payloads, and keeping privileged credentials on the backend, developers can build a reliable push notification system for React Native applications.
25. Additional Learning Resources