Send Notification to React Native App using Firebase Cloud Messaging

React Native Cloud Messaging

This is our eighth post of React Native Firebase series, in this example we will see what is Firebase Cloud Messaging? Messages Types, how to send cloud message? how to receive Firebase Cloud Message in React Native App? So Let’s start with the Firebase Cloud Messaging in React Native Example.

Firebase Cloud Messaging

Firebase Cloud Messaging is a cross-platform cloud solution for messages and notifications for Android, iOS, and web applications, which is available for free. Using Firebase Cloud Messaging(FCM), we can easily notify a client app about new updates or can send offers or exiting messages to keep them engaged. FCM is the best way to drive user re-engagement and retention. We can also use FCM for the instant messaging(Chat app) as a message can transfer a payload of up to 4KB to a client app.

Message Types

With FCM, you can send two types of messages to clients:

  • Notification messages, sometimes thought of as “display messages.” These are handled by the FCM SDK automatically
  • Data messages, which are handled by the client app

Notification messages contain a predefined set of user-visible keys. Data messages, by contrast, contain only your user-defined custom key-value pairs.

Notification messages can contain an optional data payload which can help you to send data in the notification message as well. Maximum payload for both message types is 4KB, except when sending messages from the Firebase console, which enforces a 1024 character limit.

You can see About FCM Messages to know more about Notification type.

Example Description

In this example we will setup Firebase Cloud Messaging environment in our React Native App and will send notification from Firebase Console. Sending a Firebase Cloud Message from the console is not practical so we have create a node server using Firebase Admin SDK which can help us to send the notification. Let’s get started with the setup and code.

To Make a React Native App

Getting started with React Native will help you to know more about the way you can make a React Native project. We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run

npm install -g react-native-cli

Run the following commands to create a new React Native project

react-native init ProjectName

If you want to start a new project with a specific React Native version, you can use the --version argument:

react-native init ProjectName --version X.XX.X
react-native init ProjectName --version react-native@next

This will make a project structure with an index file named App.js in your project directory.

Integration of Firebase SDK

For starting with any of the React Native Firebase Example you will need to integrate Firebase in your app, I have specially made a separate post in detail for this where you will see point to point process to add Firebase in your React Native App for Android and iOS both.

Please visit How to Integrate Firebase in Android and iOS App and come back for the next step.

Once you are done with the Firebase integration you can install the further dependencies.

Installation of Dependencies

To install the dependencies open the terminal and jump into your project using

cd ProjectName

For the React Native Firebase we need to install and setup the app module

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

Now install the messaging module

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

This command will copy all the dependencies into your node_module directory. –save is optional, it is just to update the dependency in your package.json file.

CocoaPods Installation

After the updation of React Native 0.60, they have introduced autolinking so we do not require to link the library but for iOS we need to install the pods. So to install the pods use

cd ios/ && pod install --repo-update && cd ..

Code for React Native Firebase Cloud Messaging

Please open App.js in any code editor and replace the code with the following code

App.js

/*
 * #8 Send Notification to React Native App using
 * Firebase Cloud Messaging
 * https://aboutreact.com/react-native-notification-firebase-cloud-messaging
 */

// import React in our code
import React, {useEffect} from 'react';

// import all the components we are going to use
import {
  SafeAreaView,
  StyleSheet,
  View,
  Text,
  Image
} from 'react-native';

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

const TOPIC = 'MyNews';

const App = () => {
  const requestUserPermission = async () => {
    /**
     * On iOS, messaging permission must be requested by
     * the current application before messages can be
     * received or sent
     */
    const authStatus = await messaging().requestPermission();
    console.log('Authorization status(authStatus):', authStatus);
    return (
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL
    );
  };

  useEffect(() => {
    if (requestUserPermission()) {
      /**
       * Returns an FCM token for this device
       */
      messaging()
        .getToken()
        .then((fcmToken) => {
          console.log('FCM Token -> ', fcmToken);
        });
    } else console.log('Not Authorization status:', authStatus);

    /**
     * When a notification from FCM has triggered the application
     * to open from a quit state, this method will return a
     * `RemoteMessage` containing the notification data, or
     * `null` if the app was opened via another method.
     */
    messaging()
      .getInitialNotification()
      .then(async (remoteMessage) => {
        if (remoteMessage) {
          console.log(
            'getInitialNotification:' +
              'Notification caused app to open from quit state',
          );
          console.log(remoteMessage);
          alert(
            'getInitialNotification: Notification caused app to' +
            ' open from quit state',
          );
        }
      });

    /**
     * When the user presses a notification displayed via FCM,
     * this listener will be called if the app has opened from
     * a background state. See `getInitialNotification` to see
     * how to watch for when a notification opens the app from
     * a quit state.
     */
    messaging().onNotificationOpenedApp(async (remoteMessage) => {
      if (remoteMessage) {
        console.log(
          'onNotificationOpenedApp: ' +
            'Notification caused app to open from background state',
        );
        console.log(remoteMessage);
        alert(
          'onNotificationOpenedApp: Notification caused app to' +
          ' open from background state',
        );
      }
    });

    /**
     * Set a message handler function which is called when
     * the app is in the background or terminated. In Android,
     * a headless task is created, allowing you to access the
     * React Native environment to perform tasks such as updating
     * local storage, or sending a network request.
     */
    messaging().setBackgroundMessageHandler(
      async (remoteMessage) => {
        console.log(
          'Message handled in the background!',
          remoteMessage
        );
    });

    /**
     * When any FCM payload is received, the listener callback
     * is called with a `RemoteMessage`. Returns an unsubscribe
     * function to stop listening for new messages.
     */
    const unsubscribe = messaging().onMessage(
      async (remoteMessage) => {
        alert('A new FCM message arrived!');
        console.log(
          'A new FCM message arrived!',
          JSON.stringify(remoteMessage)
        );
      }
    );

    /**
     * Apps can subscribe to a topic, which allows the FCM
     * server to send targeted messages to only those devices
     * subscribed to that topic.
     */
    messaging()
      .subscribeToTopic(TOPIC)
      .then(() => {
        console.log(`Topic: ${TOPIC} Suscribed`);
      });

    return () => {
      unsubscribe;
      /**
       * Unsubscribe the device from a topic.
       */
      // messaging().unsubscribeFromTopic(TOPIC);
    };
  }, []);

  return (
    <SafeAreaView style={styles.container}>
      <View style={styles.container}>
        <Text style={styles.titleText}>
          Send Notification to React Native App
        </Text>
        <Text style={styles.textStyle}>using</Text>
        <Image
          source={require('./Image/firebase.png')}
          style={{
            width: '90%',
            height: '50%',
            resizeMode: 'contain',
            margin: 30,
          }}
        />
        <Text style={styles.titleText}>
          Firebase Cloud Messaging
        </Text>
      </View>
      <Text
        style={{
          fontSize: 16,
          textAlign: 'center',
          color: 'white',
        }}>
        www.aboutreact.com
      </Text>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 16,
    textAlign: 'center',
    backgroundColor: '#307ecc',
  },
  titleText: {
    fontSize: 24,
    textAlign: 'center',
    fontWeight: 'bold',
    marginVertical: 10,
    color: 'white',
  },
  textStyle: {
    fontSize: 20,
    fontWeight: 'bold',
    textAlign: 'center',
    marginBottom: 10,
    color: 'white',
  },
});

export default App;

Send Cloud Message from Firebase Console

To send Firebase Cloud message from Firebase Console Open the Firebase Console, select project and select Cloud Messaging from the left menu.

react_native_cloud_message_send_notification1

Click on “Send your first message” and you will see inputs/options to compose notification. You can insert the title, text and image of the notification.

react_native_cloud_message_send_notification2

Once you click next you will see options to select your target audience. You can either select a User segment or a Topic. There are lots of options to select your audience in the User Segment option itself like you can send the message based on App Version, Languages, country/Region, user audience etc.

react_native_cloud_message_send_notification3

You can send now or can schedule the message for later

react_native_cloud_message_send_notification4

Review Message and Publish

react_native_cloud_message_send_notification5

Output Screenshots

react_native_cloud_message_send_notification6 react_native_cloud_message_send_notification7 react_native_cloud_message_send_notification8 react_native_cloud_message_send_notification9 react_native_cloud_message_send_notification10 react_native_cloud_message_send_notification11
react_native_cloud_message_send_notification12

Download Source Code

Node Server to send Firebase Cloud Messages

You can send the cloud message from the console but in practical you will need a way to trigger the cloud messages from your server. Firebase Admin SDK will help you to do that. Here is a small project in Node.js created using Firebase Admin SDK.

Before you run this project you have to get the service-account.json file to connect your server with your Firebase instance. To get the service-account.json file open console, click on the setting icon and select “Project Settings”, Once you open the project setting click on the “Service Accounts” tab, You will see and option to generate new private key. This key is the same file which we need to connect our Firebase Instance.

react_native_cloud_message_send_notification13

Downloaded service account file can have a long name with json extension, you can rename it if you want. Now you can setup node server using following steps.

1. Clone Repo

git clone https://github.com/SnehalAgrawal/about-react-dummy-firebase-apis.git

2. Jump into the directory

cd about-react-dummy-firebase-apis

3. Install node_module

npm install

4. Update the service account file path

const serviceAccount =
require("/Users/kepi/Desktop/MainRepo/service-account-file.json");

5. Run Server

npm start

This will start your server for you

react_native_cloud_message_server

Once your server is up and running you can use following URL to send notification

http://localhost:3000/notify/

This is how you can send Firebase Cloud Message in React Native App for Android and iOS. If you have any doubts or you want to share something about the topic you can comment below or contact us here. There will be more posts coming soon. Stay tuned!

Hope you liked it. 🙂

6 thoughts on “Send Notification to React Native App using Firebase Cloud Messaging”

  1. The notification does not show when the app is in the foreground state btw working fine when the app is in the background how can I solve it.

    Reply
  2. I’ve the exact same setup as above.

    How to we add styling to notification text, like I want to bold and change the colour of notification text.

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.