@react-native-firebase/appand@react-native-firebase/messaginginstalled (npm install --save @react-native-firebase/app @react-native-firebase/messagingoryarn add @react-native-firebase/app @react-native-firebase/messaging), then rebuild native apps (cd ios && pod installon iOS). From v26, New Architecture is required for packages with a native bridge.- Native Firebase config completed per Getting Started (Android
google-services.json, iOSGoogleService-Info.plist, Expo config plugin, or React Native CLI setup). - On iOS, complete iOS Messaging Setup and request notification permission (see iOS Permissions).
- On Android API 33+, request
POST_NOTIFICATIONSbefore expecting notification UI. - Register
setBackgroundMessageHandlerin the entry file beforeAppRegistry.registerComponentif you handle background/quit messages (see Cloud Messaging usage).
Notifications are an important tool used on the majority of Android & iOS applications, used to improve user experience, used to engage users with your application and much more. The Cloud Messaging module provides basic support for displaying and handling notifications.
The Firebase Cloud Messaging SDKs for Android and iOS allow for notifications to be displayed on devices when the application
is either quit or in the background. The Firebase Console, Firebase Admin SDKs and REST API all allow a notification
property to be attached to a message.
If an incoming message with this property exists, and the app is not visible (quit or in the background),
a notification is displayed on the device. However, if the application is in the foreground, an event will be delivered
containing the notification data and, by default, no visible notification will be displayed. On iOS you can opt in to presenting
foreground notifications with messaging_ios_foreground_presentation_options (see
Foreground Presentation Options (iOS)). See the Usage documentation
to learn more about handling events.
The Firebase Console provides a simple UI to allow devices to display a notification. Using the console, you can:
- Send a basic notification with custom text and images.
- Target applications which have been added to your project.
- Schedule notifications to display at a later date.
- Send recurring notifications.
- Assign conversion events for your analytical tracking.
- A/B test user interaction (called "experiments").
- Test notifications on your development devices.
The Firebase Console automatically sends a message to your devices containing a notification property which is handled
by the React Native Firebase Cloud Messaging module. See Handling Interaction to learn about how
to support user interaction.
The various Firebase Admin SDKs allow you to send messages to your users. If these messages also contain notification options, the React Native Firebase Cloud Messaging module will automatically display these notifications.
For example, when using the firebase-admin package in a Node.js environment
to send messages from a server, a notification property can be added to the message payload:
// codeblock-ignore: server-side sample that requires the firebase-admin package
const admin = require('firebase-admin');
await admin.messaging().sendEachForMulticast({
tokens: ['token_1', 'token_2'],
notification: {
title: 'Basic Notification',
body: 'This is a basic notification sent from the server!',
imageUrl: 'https://my-cdn.com/app-logo.png',
},
});The Cloud Messaging module will intercept these messages and if the notification property is available, it will display
a system notification when the app is in the background or quit. In the foreground, no system notification is shown by
default (on iOS, unless messaging_ios_foreground_presentation_options is set); the payload is delivered to onMessage
instead. Messages with both a notification and data property follow the same split: foreground uses onMessage;
background and quit show a system notification and, on Android, call setBackgroundMessageHandler (not onMessage). On
iOS, a notification message in the background or quit state reaches setBackgroundMessageHandler only when it also sets
content-available. See the message-handler table on Usage.
The different Admin SDKs available have similar implementation details on how to add a custom notification property to
the FCM payload, however the Cloud Messaging module will handle all requests. To learn more, view the
Firebase Admin SDK documentation for your chosen admin SDK. For those using the
HTTP implementation, view the REST Cloud Messaging
reference.
If you are unable to use a Firebase Admin SDK, Firebase also provides support for sending messages to devices via a POST request:
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"token":"bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"data":{},
"notification":{
"body":"This is an FCM notification message!",
"title":"FCM Message"
}
}
}To learn more about the REST API, view the Firebase documentation, and select the "REST" tab under the code examples.
When a user interacts with your notification by pressing on it, the default behavior is to open the application (since notifications via FCM only display when the application is in the background by default, the application will always open).
In many cases, it is useful to detect whether the application was opened by pressing on a notification (so you could open a specific screen for example). The API provides two APIs for handling interaction:
getInitialNotification: When the application is opened from a quit state. It resolves theRemoteMessageornull. On Android a given notification is returned once, and the call resolvesnull(with a logged warning) when the current activity is not ready yet, so call it again later in the React lifecycle.onNotificationOpenedApp: When the application is running, but in the background. It returns a function that removes the listener.
These fire for the default notification open (user taps the notification body). They do not fire for custom notification-category actions or dismiss, so do not route custom-action navigation through them. Handle those interactions with a local notification library of your choice.
To handle both scenarios, the code can be executed during setup. For example, using React Navigation we can set an initial route when the app is opened from a quit state, and push to a new screen when the app is in a background state:
// codeblock-ignore: requires the @react-navigation/native and @react-navigation/stack packages
import React from 'react';
import { Linking, ActivityIndicator, View, Text } from 'react-native';
import {
getMessaging,
getInitialNotification,
onNotificationOpenedApp,
} from '@react-native-firebase/messaging';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
const Stack = createStackNavigator();
const NAVIGATION_IDS = ['home', 'post', 'settings'];
const messaging = getMessaging();
function HomeScreen() {
return (
<View>
<Text>Home</Text>
</View>
);
}
function PostScreen() {
return (
<View>
<Text>Post</Text>
</View>
);
}
function SettingsScreen() {
return (
<View>
<Text>Settings</Text>
</View>
);
}
function buildDeepLinkFromNotificationData(data) {
const navigationId = data?.navigationId;
if (!NAVIGATION_IDS.includes(navigationId)) {
console.warn('Unverified navigationId', navigationId);
return null;
}
if (navigationId === 'home') {
return 'myapp://home';
}
if (navigationId === 'settings') {
return 'myapp://settings';
}
const postId = data?.postId;
if (typeof postId === 'string') {
return `myapp://post/${postId}`;
}
console.warn('Missing postId');
return null;
}
const linking = {
prefixes: ['myapp://'],
config: {
initialRouteName: 'Home',
screens: {
Home: 'home',
Post: 'post/:id',
Settings: 'settings',
},
},
async getInitialURL() {
const url = await Linking.getInitialURL();
if (typeof url === 'string') {
return url;
}
const message = await getInitialNotification(messaging);
const deeplinkURL = buildDeepLinkFromNotificationData(message?.data);
if (typeof deeplinkURL === 'string') {
return deeplinkURL;
}
},
subscribe(listener) {
const onReceiveURL = ({ url }) => listener(url);
const linkingSubscription = Linking.addEventListener('url', onReceiveURL);
const unsubscribe = onNotificationOpenedApp(messaging, remoteMessage => {
const deepLinkUrl = buildDeepLinkFromNotificationData(remoteMessage.data);
if (typeof deepLinkUrl === 'string') {
listener(deepLinkUrl);
}
});
return () => {
linkingSubscription.remove();
unsubscribe();
};
},
};
function App() {
return (
<NavigationContainer linking={linking} fallback={<ActivityIndicator animating />}>
<Stack.Navigator>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Post" component={PostScreen} />
<Stack.Screen name="Settings" component={SettingsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default App;A Messaging-only version without React Navigation:
import React, { useEffect } from 'react';
import { View, Text } from 'react-native';
import {
getMessaging,
getInitialNotification,
onNotificationOpenedApp,
} from '@react-native-firebase/messaging';
function App() {
useEffect(() => {
const messaging = getMessaging();
getInitialNotification(messaging).then(remoteMessage => {
if (remoteMessage) {
console.log('Opened from quit state via notification:', remoteMessage.notification);
}
});
const unsubscribe = onNotificationOpenedApp(messaging, remoteMessage => {
console.log('Opened from background via notification:', remoteMessage.notification);
});
return unsubscribe;
}, []);
return (
<View>
<Text>Notification interaction listeners registered</Text>
</View>
);
}
export default App;Quick Tip: On Android you can test receiving remote notifications on the emulator. On iOS,
use a physical device for real APNs tokens and delivery. On ARM64 Simulator,
registerDeviceForRemoteMessages may reject with messaging/registration-timeout (UIKit register
is skipped intentionally so the main thread cannot hang), see
Auto Registration (iOS) and
Migrating to v26, iOS APNs registration.
This is the latest way to register a device with FCM.
To send messages to a device, register it with register(messaging) and read its Firebase Installation ID (FID) from onRegistered. Installation ID messaging is off by default, see Installation ID messaging to opt in.
On iOS, React Native Firebase Messaging automatically registers the device with APNs by default. You only need to
manually call registerDeviceForRemoteMessages(messaging) if you disabled
auto-registration with messaging_ios_auto_register_for_remote_messages in firebase.json, or if you otherwise
need to register before the app has registered for remote messages. See
Auto Registration (iOS) for the manual registration example.
(register() does not replace registerDeviceForRemoteMessages.)
import {
getMessaging,
onRegistered,
register,
registerDeviceForRemoteMessages,
} from '@react-native-firebase/messaging';
async function registerDevice() {
const messaging = getMessaging();
// Optional: not needed in most cases, and a no-op if already registered.
await registerDeviceForRemoteMessages(messaging);
const unsubscribe = onRegistered(messaging, installationId => {
console.log('FID:', installationId);
});
await register(messaging);
// Call unsubscribe() when the listener is no longer needed, for example in an effect cleanup.
return unsubscribe;
}The Messaging token APIs getToken, deleteToken and onTokenRefresh are deprecated. Firebase JS 12.14+, Android Messaging 25.1+ and Apple 12.18+ deprecated the FCM token APIs in favor of Installation ID registration (register / onRegistered, and unregister / onUnregistered in place of deleteToken). The token APIs still work while Installation ID messaging is off. Once you opt in, getToken and deleteToken reject and onTokenRefresh throws with messaging/token-api-disabled.
To send messages to a device, you need the FCM token for it, which you can get using getToken(messaging).
On iOS, React Native Firebase Messaging automatically registers the device with APNs by default. You only need to
manually call registerDeviceForRemoteMessages(messaging) before getToken(messaging) if you disabled
auto-registration with messaging_ios_auto_register_for_remote_messages in firebase.json, or if you otherwise call
getToken(messaging) before the app has registered for remote messages. See
Auto Registration (iOS) for the manual registration example.
(register() for FID messaging does not replace registerDeviceForRemoteMessages.)
// DEPRECATED: prefer register() above. Still works while Installation ID messaging is off.
import {
getMessaging,
registerDeviceForRemoteMessages,
getToken,
} from '@react-native-firebase/messaging';
const messaging = getMessaging();
// Optional: not needed in most cases, and a no-op if already registered.
await registerDeviceForRemoteMessages(messaging);
const token = await getToken(messaging);
console.log('FCM token:', token);
Core / App