react native CLI firebase FCM forground and background push notification with full source code
To set up Firebase Cloud Messaging (FCM) push notifications in a React Native app using React Native CLI, follow these steps:
1. Set Up Firebase Project
Create a Firebase Project:
- Go to the Firebase Console.
- Click on "Add project" and follow the instructions.
Add an Android App to the Firebase Project:
- In the Firebase console, select your project.
- Click on the Android icon to add an Android app.
- Register your app with the package name (e.g.,
com.yourappname
). - Download the
google-services.json
file and place it in theandroid/app
directory of your React Native project.
Add an iOS App to the Firebase Project:
- In the Firebase console, select your project.
- Click on the iOS icon to add an iOS app.
- Register your app with the iOS bundle ID.
- Download the
GoogleService-Info.plist
file and place it in theios/yourprojectname
directory.
2. Install React Native Firebase Dependencies
Install the required dependencies for Firebase and FCM:
bashnpm install @react-native-firebase/app @react-native-firebase/messaging
3. Configure Firebase for Android
Edit the android/build.gradle
file to include the Google services plugin:
gradlebuildscript { dependencies { // Add this line classpath 'com.google.gms:google-services:4.3.10' } }
Edit the android/app/build.gradle
file to apply the Google services plugin and include Firebase dependencies:
gradleapply plugin: 'com.google.gms.google-services' dependencies { // Add these lines implementation platform('com.google.firebase:firebase-bom:28.3.0') implementation 'com.google.firebase:firebase-messaging' }
4. Configure Firebase for iOS
Edit the ios/Podfile
to include Firebase pods:
rubyplatform :ios, '10.0'
target 'YourAppTargetName' do
# Add these lines
pod 'Firebase/Core'
pod 'Firebase/Messaging'
end
Install the pods:
bashcd ios
pod install
cd ..
5. Request Permissions for Notifications
For iOS, you need to request permission to send notifications:
Edit AppDelegate.m
to include notification setup:
objective#import "AppDelegate.h" #import <Firebase.h> #import "RNFBMessagingModule.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([FIRApp defaultApp] == nil) { [FIRApp configure]; } if (@available(iOS 10.0, *)) { [UNUserNotificationCenter currentNotificationCenter].delegate = self; } // ... return YES; } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [RNFBMessagingModule didRegisterForRemoteNotificationsWithDeviceToken:deviceToken]; } @end
Request notification permissions in your React Native component:
javascriptimport messaging from '@react-native-firebase/messaging';
async function requestUserPermission() {
const authStatus = await messaging().requestPermission();
const enabled =
authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
authStatus === messaging.AuthorizationStatus.PROVISIONAL;
if (enabled) {
console.log('Authorization status:', authStatus);
}
}
requestUserPermission();
6. Handle Notifications
Set up notification handlers in your React Native code:
javascriptimport React, { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';
import { Alert } from 'react-native';
const App = () => {
useEffect(() => {
const unsubscribe = messaging().onMessage(async remoteMessage => {
Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
});
messaging().setBackgroundMessageHandler(async remoteMessage => {
console.log('Message handled in the background!', remoteMessage);
});
return unsubscribe;
}, []);
return (
// Your app component JSX
);
};
export default App;
7. Test Notifications
To test push notifications:
- Get the device token using
messaging().getToken()
. - Send a test message from the Firebase console or using Postman with the device token.
By following these steps, you should be able to set up Firebase Cloud Messaging for push notifications in your React Native application using the React Native CLI.