Codementor Events

React Native Push Notifications with Firebase 2020

Published Nov 12, 2019Last updated Aug 30, 2020

Updated May 26, 2020

Study app for implementing Push Notifications with Firebase in a React Native mobile app this is part of Alameda Dev Explorations.

In this tutorial we are going to implement Push Notifications in a React Native mobile aplicación, our notification backend will be in Firebase for ease of use, but you can use your own system.

First create a project in your Google Firebase Console https://console.firebase.google.com/

Also create your React Native project and enter it"s directory
react-native init RNPushNotifications

Adding Firebase to your app

Register your app in Firebase and follow the configuration steps for Android and for iOS.
Download your GoogleService-Info.plist and google-services.json. Don"t forget to place them in the correct folder for each platform

Android:

iOS:

Add and link the React Native Firebase package to your app

yarn add @react-native-firebase/app
yarn add @react-native-firebase/messaging
cd ios ; pod install ; cd ..

Follow the installation instruction for the latest release here:

Android: https://rnfirebase.io/#2-android-setup
iOS: https://rnfirebase.io/#3-ios-setup

Generate APNS certificate for iOS Push Notifications

On iOS you need to Generate an APNS certificate in order to receive Push Notifications.
Apple Push Notification Service (commonly referred to as Apple Notification Service or APNS) is a platform service created by Apple Inc. that enables third party application developers to send push notifications to iOS users. You must have a Paid Apple Developer account to create certificates.

  • Login to Apple developer account and click "Certificates, IDs & Profiles"
    (https://developer.apple.com/)

  • Select "Identifiers" form the left menu

  • Click the Plus (+) sign above the center list

  • Choose "App IDs" from the selection options

  • Fill out your Description, Bundle ID, and choose "Push Notifications" form the options.

  • Confirm your information and click "Register"

Generate a Certificate from Keychain Access

  • Launch the Keychain Access application in your Mac OS X and Select Keychain Access -> Certificate Assistant -> Request a Certificate From a Certificate Authority

  • Enter email address and check the "Saved to disk" option, then click Continue

Generate a Development Certificate

  • Go back to developer account and select app from App IDs and click on it to Edit

  • Scroll Down to Push Notifications and click on Configure

  • Under Development SSL Certificate click Create Certificate

  • Choose the file you created in the previous step and click Continue

  • Download Development Certificate to finish process

Generate APNS .p12 certificate

  • Double click Development certificate generated in previous step to add it to Keychain Access. Go to Keychain Access, select login keychain and My Certificate from side menu. Find app certificate and right click to export it

  • Enter certificate name and click Save

  • Enter password for certificate and click OK

  • Enter your computer admin password to finish the process

These are all the steps to create a development certificate, now we continue to add PushNotifications to our app

Configuration iOS project

On Xcode go to your project settings, under Singing and Capabilities, add these two:

  • Push notifications

  • Background Modes — Check only Remote Notifications

iOS prevents messages containing notification (or 'alert') payloads from being displayed unless you have received explicit permission from the user.

This module provides a requestPermission method which triggers a native permission dialog requesting the user's permission:

import messaging from '@react-native-firebase/messaging';
...
useEffect(() => {
    requestUserPermission();
   }, []);

  requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      console.log('Authorization status:', authStatus);
    }
  }
...

The permissions API for iOS provides much more fine-grain control over permissions and how they're handled within your application. To learn more, view the advanced iOS Permissions documentation.

On Android, you do not need to request user permission. This method can still be called on Android devices; however, and will always resolve successfully.

Implementing FCM tokens in your app

Lets go to our App.js and add some code

After everything set up and configured for the Android and iOS (in Xcode), now, we have to implement the FCM push notification in React Native side using React Native Firebase module. Just open and edit App.js then add or modify these imports of Firebase, React Hooks useEffect, and React Native Alert.

import React, {Fragment,useEffect} from "react";
import {
 SafeAreaView,
 StyleSheet,
 ScrollView,
 View,
 Text,
 StatusBar,
 Alert
} from "react-native";
import firebase from "react-native-firebase";

Change the method that runs checks Permissions.

  requestUserPermission = async () => {
    const authStatus = await messaging().requestPermission();
    const enabled =
      authStatus === messaging.AuthorizationStatus.AUTHORIZED ||
      authStatus === messaging.AuthorizationStatus.PROVISIONAL;

    if (enabled) {
      getFcmToken() //<---- Add this
      console.log('Authorization status:', authStatus);
    }
  }

Add a function to get FCM token from the Firebase and show the token to the React Native Alert.

  getFcmToken = async () => {
    const fcmToken = await messaging().getToken();
    if (fcmToken) {
     console.log(fcmToken);
     console.log("Your Firebase Token is:", fcmToken);
    } else {
     console.log("Failed", "No token received");
    }
  }

After having configured everything correctly we can test directly from the firebase console:

  • Go to the Cloud Messaging option in the left pane.
  • Click on Send your first message
  • Enter your test text, select the Android application to which you want to send the application and click Send.

You can use the FCM token to test your notifications.

In the console, you will see the FCM token, you can copy and paste it in the Firebase Console for your testings

Click to watch the Video

Other functions

Foreground state messages

To listen to messages in the foreground, call the onMessage method inside of your application code. Code executed via this handler has access to React context and is able to interact with your application (e.g. updating the state or UI).

For example, the React Native Alert API could be used to display a new Alert each time a message is delivered'

import { Alert } from 'react-native';
...
  useEffect(() => {
    requestUserPermission();
    const unsubscribe = messaging().onMessage(async remoteMessage => {
      Alert.alert('A new FCM message arrived!', JSON.stringify(remoteMessage));
    });

    return unsubscribe;
   }, []);
...

The remoteMessage property contains all of the information about the message sent to the device from FCM, including any custom data (via the data property) and notification data. To learn more, view the RemoteMessage API reference.

If the RemoteMessage payload contains a notification property when sent to the onMessage handler, the device will not show any notification to the user. Instead, you could trigger a local notification or update the in-app UI to signal a new notification.

Please see ther uses for background notifications here
https://rnfirebase.io/messaging/usage#foreground-state-messages

Now you can send Push Notifications based on app platform, devices, dates registered, etc. Google Firebase has many options for sending these notifications.

Discover and read more posts from Osledy Bazó
get started
post comments20Replies
JuanCarlos
4 years ago

Great article! It works for me until the part about sending a message to an iOS device. And that’s because it’s missing a configuration of something else.
You must to create and download a .p8 key from https://developer.apple.com/account/resources/authkeys/list and them from “Project Settings”, in Firebase Console, go to “Cloud Messaging” tab and add the APNs Authentication Key (.p8 file). After that it will be possible to send notifications to iOS devices.

zeeshan Javed
5 years ago

Hi
Can you please make a full example of v6 firebase pushed notification?
Highly appreciated for your response.

Diego Magalhães
4 years ago

Firebase V6 Push Notification is not yet implemented. :(

Aymen Amara
5 years ago

Hi
Thank you so much!
I implemented our code and it was great, but I want to send notification for only authenticated users

Osledy Bazó
5 years ago

Hello Aymen. Thanks for your comment. You could register only the authenticated users. Or when receiving a notification, check if the user is authenticated. Just some ideas. Let me know if either helped you.

Aymen Amara
5 years ago

Thanks for answering me so quick
I checked if the user is authenticated in useEffect and even before including the <Notif /> and the test doesn’t work

Show more replies