/firebase-tutorials

How to handle FCM in React Native?

Learn how to integrate Firebase Cloud Messaging in your React Native app. Follow our step-by-step guide to set up, configure, and test notifications.

Matt Graham, CEO of Rapid Developers

Book a call with an Expert

Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.

Book a free No-Code consultation

How to handle FCM in React Native?

 

Step 1: Set Up Firebase Project

 

To begin with, you need a Firebase project. If you don’t have one, create it by going to the Firebase Console and clicking "Add Project". Follow the on-screen instructions to set it up.

 

Step 2: Add Firebase to Your React Native App

 

You'll need to add Firebase SDK to your React Native project. Use the following commands:


npm install @react-native-firebase/app
npm install @react-native-firebase/messaging

Ensure that you have installed the React Native Firebase Messaging package to enable the use of Firebase Cloud Messaging (FCM).

 

Step 3: Configure Firebase for iOS and Android

 

iOS Configuration:

  1. Open your React Native project in Xcode.
  2. Click on your project in the left sidebar.
  3. Add your GoogleService-Info.plist file by dragging it into the Xcode project.
  4. Enable push notifications and background modes (especially “Remote notifications”) under your target’s capabilities.

Android Configuration:

  1. Add the google-services.json file to the android/app directory.
  2. Inside android/build.gradle, add:

buildscript {
    dependencies {
        // Add this line
        classpath 'com.google.gms:google-services:4.3.10'
    }
}
  1. In android/app/build.gradle, apply the google-services plugin by adding this line at the bottom:

apply plugin: 'com.google.gms.google-services'

 

Step 4: Request User Permissions

 

Before you can receive notifications, request user permissions. Update your React Native code for permissions as follows:


import 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();

 

Step 5: Get the FCM Token

 

Retrieve the device token, which is required to send notifications to the device.


async function getToken() {
    const fcmToken = await messaging().getToken();
    if (fcmToken) {
        console.log('Your Firebase Cloud Messaging Token is:', fcmToken);
    } else {
        console.log('Failed to get the token.');
    }
}

getToken();

Ensure you securely store this token in your server or within a secure environment for later use in sending notifications.

 

Step 6: Handle Incoming Messages

 

Use the following snippets to handle foreground and background messages.

Foreground Messages:


import { useEffect } from 'react';
import messaging from '@react-native-firebase/messaging';

useEffect(() => {
    const unsubscribe = messaging().onMessage(async remoteMessage => {
        console.log('A new FCM message arrived!', JSON.stringify(remoteMessage));
    });

    return unsubscribe;
}, []);

Background and Quit State Messages:

Add this at the top level of your application, e.g., index.js or App.js:


import messaging from '@react-native-firebase/messaging';

messaging().setBackgroundMessageHandler(async remoteMessage => {
    console.log('Message handled in the background!', remoteMessage);
});

 

Step 7: Testing FCM

 

Ensure the application is installed on a real device (emulators may not work for push notifications). In the Firebase Console, navigate to Cloud Messaging under the Engage section. Click on "Send your first message" and fill in the fields as required. Here, you can set the target to your app's package name and include the device token for precise targeting. Send the message and observe your app for notifications both in the foreground and background.

 

By following these detailed steps, you should be able to handle FCM in your React Native application effectively. Troubleshoot any issues by checking logs and ensuring all configurations are correctly applied.

Want to explore opportunities to work with us?

Connect with our team to unlock the full potential of no-code solutions with a no-commitment consultation!

Book a Free Consultation

Client trust and success are our top priorities

When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.

Rapid Dev was an exceptional project management organization and the best development collaborators I've had the pleasure of working with. They do complex work on extremely fast timelines and effectively manage the testing and pre-launch process to deliver the best possible product. I'm extremely impressed with their execution ability.

CPO, Praction - Arkady Sokolov

May 2, 2023

Working with Matt was comparable to having another co-founder on the team, but without the commitment or cost. He has a strategic mindset and willing to change the scope of the project in real time based on the needs of the client. A true strategic thought partner!

Co-Founder, Arc - Donald Muir

Dec 27, 2022

Rapid Dev are 10/10, excellent communicators - the best I've ever encountered in the tech dev space. They always go the extra mile, they genuinely care, they respond quickly, they're flexible, adaptable and their enthusiasm is amazing.

Co-CEO, Grantify - Mat Westergreen-Thorne

Oct 15, 2022

Rapid Dev is an excellent developer for no-code and low-code solutions.
We’ve had great success since launching the platform in November 2023. In a few months, we’ve gained over 1,000 new active users. We’ve also secured several dozen bookings on the platform and seen about 70% new user month-over-month growth since the launch.

Co-Founder, Church Real Estate Marketplace - Emmanuel Brown

May 1, 2024 

Matt’s dedication to executing our vision and his commitment to the project deadline were impressive. 
This was such a specific project, and Matt really delivered. We worked with a really fast turnaround, and he always delivered. The site was a perfect prop for us!

Production Manager, Media Production Company - Samantha Fekete

Sep 23, 2022