0
# React Native Firebase Messaging
1
2
React Native Firebase Messaging provides comprehensive Firebase Cloud Messaging (FCM) integration for React Native applications. It enables cross-platform push notifications with native performance, supporting both Android and iOS platforms with advanced features like background message handling, notification customization, and topic subscriptions.
3
4
## Package Information
5
6
- **Package Name**: @react-native-firebase/messaging
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @react-native-firebase/messaging`
10
- **Dependencies**: Requires `@react-native-firebase/app` as peer dependency
11
12
## Core Imports
13
14
ESM/TypeScript:
15
16
```typescript
17
import messaging from '@react-native-firebase/messaging';
18
import { firebase } from '@react-native-firebase/messaging';
19
```
20
21
Modular API:
22
23
```typescript
24
import {
25
getMessaging,
26
getToken,
27
onMessage,
28
requestPermission
29
} from '@react-native-firebase/messaging';
30
```
31
32
CommonJS:
33
34
```javascript
35
const messaging = require('@react-native-firebase/messaging').default;
36
```
37
38
## Basic Usage
39
40
```typescript
41
import messaging from '@react-native-firebase/messaging';
42
43
// Initialize and request permissions (iOS)
44
const authStatus = await messaging().requestPermission();
45
if (authStatus === messaging.AuthorizationStatus.AUTHORIZED) {
46
// Get FCM registration token
47
const token = await messaging().getToken();
48
console.log('FCM Token:', token);
49
50
// Listen for foreground messages
51
const unsubscribe = messaging().onMessage(async remoteMessage => {
52
console.log('Message:', remoteMessage.data);
53
});
54
55
// Setup background message handler
56
messaging().setBackgroundMessageHandler(async remoteMessage => {
57
console.log('Background message:', remoteMessage);
58
});
59
}
60
```
61
62
## Architecture
63
64
React Native Firebase Messaging is built around several key components:
65
66
- **Dual API Patterns**: Both namespaced (`firebase.messaging()`) and modular (`getMessaging()`) APIs
67
- **Native Bridge**: Communicates with native Firebase SDKs on Android and iOS
68
- **Message Lifecycle**: Handles messages in foreground, background, and quit states
69
- **Token Management**: Automatic token generation and refresh handling
70
- **Platform Abstraction**: Unified API across platforms with platform-specific features
71
- **Background Processing**: Headless task execution for background message handling
72
73
## Capabilities
74
75
### Token Management
76
77
Core FCM token operations for device registration and authentication with Firebase servers.
78
79
```typescript { .api }
80
function getToken(options?: GetTokenOptions & NativeTokenOptions): Promise<string>;
81
function deleteToken(options?: NativeTokenOptions): Promise<void>;
82
function onTokenRefresh(listener: (token: string) => any): () => void;
83
```
84
85
[Token Management](./token-management.md)
86
87
### Message Handling
88
89
Complete message lifecycle management for foreground, background, and app launch scenarios.
90
91
```typescript { .api }
92
function onMessage(listener: (message: RemoteMessage) => any): () => void;
93
function onNotificationOpenedApp(listener: (message: RemoteMessage) => any): () => void;
94
function getInitialNotification(): Promise<RemoteMessage | null>;
95
function setBackgroundMessageHandler(handler: (message: RemoteMessage) => Promise<any>): void;
96
```
97
98
[Message Handling](./message-handling.md)
99
100
### Permissions & Registration
101
102
Permission management and device registration for receiving notifications, primarily for iOS.
103
104
```typescript { .api }
105
function requestPermission(permissions?: IOSPermissions): Promise<AuthorizationStatus>;
106
function hasPermission(): Promise<AuthorizationStatus>;
107
function registerDeviceForRemoteMessages(): Promise<void>;
108
function unregisterDeviceForRemoteMessages(): Promise<void>;
109
```
110
111
[Permissions & Registration](./permissions-registration.md)
112
113
### Topic Management
114
115
Subscribe and unsubscribe devices to/from topics for targeted messaging campaigns.
116
117
```typescript { .api }
118
function subscribeToTopic(topic: string): Promise<void>;
119
function unsubscribeFromTopic(topic: string): Promise<void>;
120
```
121
122
[Topic Management](./topic-management.md)
123
124
### iOS Specific Features
125
126
Apple Push Notification service (APNs) integration and iOS-specific messaging features.
127
128
```typescript { .api }
129
function getAPNSToken(): Promise<string | null>;
130
function setAPNSToken(token: string, type?: string): Promise<void>;
131
function getDidOpenSettingsForNotification(): Promise<boolean>;
132
function setOpenSettingsForNotificationsHandler(handler: (message: RemoteMessage) => any): void;
133
```
134
135
[iOS Features](./ios-features.md)
136
137
### Android Specific Features
138
139
Android-specific messaging capabilities including upstream messaging and message lifecycle events.
140
141
```typescript { .api }
142
function sendMessage(message: RemoteMessage): Promise<void>;
143
function onDeletedMessages(listener: () => void): () => void;
144
function onMessageSent(listener: (messageId: string) => any): () => void;
145
function onSendError(listener: (evt: SendErrorEvent) => any): () => void;
146
```
147
148
[Android Features](./android-features.md)
149
150
### Configuration & Analytics
151
152
Configuration management and analytics settings for Firebase Cloud Messaging.
153
154
```typescript { .api }
155
readonly isAutoInitEnabled: boolean;
156
function setAutoInitEnabled(enabled: boolean): Promise<void>;
157
readonly isDeliveryMetricsExportToBigQueryEnabled: boolean;
158
function setDeliveryMetricsExportToBigQuery(enabled: boolean): Promise<void>;
159
readonly isNotificationDelegationEnabled: boolean;
160
function setNotificationDelegationEnabled(enabled: boolean): Promise<void>;
161
function getIsHeadless(): Promise<boolean>;
162
function isSupported(): Promise<boolean>;
163
function experimentalSetDeliveryMetricsExportedToBigQueryEnabled(enabled: boolean): Promise<void>; // Web only
164
```
165
166
## Global Types
167
168
```typescript { .api }
169
interface RemoteMessage {
170
messageId?: string;
171
messageType?: string;
172
from?: string;
173
to?: string;
174
collapseKey?: string;
175
sentTime?: number;
176
ttl?: number;
177
data?: { [key: string]: string | object };
178
notification?: Notification;
179
contentAvailable?: boolean; // iOS
180
mutableContent?: boolean; // iOS
181
category?: string; // iOS
182
threadId?: string; // iOS
183
fcmOptions?: FcmOptions;
184
priority?: MessagePriority; // Android
185
originalPriority?: MessagePriority; // Android
186
}
187
188
interface Notification {
189
title?: string;
190
body?: string;
191
titleLocKey?: string;
192
titleLocArgs?: string[];
193
bodyLocKey?: string;
194
bodyLocArgs?: string[];
195
icon?: string; // Web
196
image?: string; // Web
197
ios?: {
198
subtitle?: string;
199
subtitleLocKey?: string;
200
subtitleLocArgs?: string[];
201
badge?: string;
202
sound?: string | NotificationIOSCriticalSound;
203
};
204
android?: {
205
sound?: string;
206
channelId?: string;
207
color?: string;
208
smallIcon?: string;
209
imageUrl?: string;
210
link?: string;
211
count?: number;
212
clickAction?: string;
213
priority?: NotificationAndroidPriority;
214
ticker?: string;
215
visibility?: NotificationAndroidVisibility;
216
};
217
}
218
219
interface NotificationIOSCriticalSound {
220
critical?: boolean;
221
name: string;
222
volume?: number;
223
}
224
225
interface FcmOptions {
226
link?: string;
227
analyticsLabel?: string;
228
}
229
230
interface IOSPermissions {
231
alert?: boolean;
232
announcement?: boolean;
233
badge?: boolean;
234
criticalAlert?: boolean;
235
carPlay?: boolean;
236
provisional?: boolean;
237
sound?: boolean;
238
providesAppNotificationSettings?: boolean;
239
}
240
241
interface GetTokenOptions {
242
vapidKey?: string; // Web
243
serviceWorkerRegistration?: ServiceWorkerRegistration; // Web
244
}
245
246
interface NativeTokenOptions {
247
appName?: string; // Android
248
senderId?: string; // iOS
249
}
250
251
interface SendErrorEvent {
252
messageId: string;
253
error: NativeFirebaseError;
254
}
255
256
enum AuthorizationStatus {
257
NOT_DETERMINED = -1, // iOS
258
DENIED = 0,
259
AUTHORIZED = 1,
260
PROVISIONAL = 2, // iOS 12+
261
EPHEMERAL = 3, // iOS 14+
262
}
263
264
enum MessagePriority {
265
PRIORITY_UNKNOWN = 0,
266
PRIORITY_HIGH = 1,
267
PRIORITY_NORMAL = 2,
268
}
269
270
enum NotificationAndroidPriority {
271
PRIORITY_MIN = -2,
272
PRIORITY_LOW = -1,
273
PRIORITY_DEFAULT = 0,
274
PRIORITY_HIGH = 1,
275
PRIORITY_MAX = 2,
276
}
277
278
enum NotificationAndroidVisibility {
279
VISIBILITY_SECRET = -1,
280
VISIBILITY_PRIVATE = 0,
281
VISIBILITY_PUBLIC = 1,
282
}
283
```