Push Notifications in a React Native Application using Firebase, Node.js and Express.js

Guna Shekar Proddaturi
tech@iiit-gwalior
Published in
6 min readJan 16, 2021

Push Notifications are one of the key features one can have in their mobile app to keep their users engaged. This article will give you an overview on how you can add the push notifications feature to your React Native mobile application using Firebase Cloud Messaging(FCM) service.

This article assumes you have a fair knowledge of Node.js and React Native. Also, feel free to either use npm or yarn in the following tutorial, I have used npm for the server and yarn for the mobile app.

Starting off, you’ll need to set up a project on Firebase.

Go to https://console.firebase.google.com/ and login if necessary. Click on “Add Project”. Give your project a name, “push-notifications-test” in this case and click on “Continue”. In the next page you might be asked if you want to enable Google Analytics for this project and it is turned on by default and is also recommended. Click on “Continue”. In the next tab, select your account or create a new one and click on “Create Project”. It might take a few seconds before your project is set up.

On the top left, beside “Project Overview”, you’ll find a settings icon. Select that and click on “Project Settings”.

Go to the “Service accounts” tab and click on “Generate new private key”. You’ll see that a json file gets downloaded. You’ll be needing this private key to access the Firebase SDK.

Let’s now set up a Node.js + Express.js server to create an API to send push notifications. Make sure you have Node.js and NPM installed in your systems.

Run the following commands to create an NPM repository:-

mkdir push-notifications-test
cd push-notifications-test
npm init -y

Open this directory in any text editor of your choice and you’ll see a package.json file.

Install the required packages:-

npm i express body-parser firebase-admin

Place the Firebase private key file that you downloaded at the topmost level(the push-notifications-test directory) with the name “firebase.json”. This file has your private key and hence should not be pushed into version control. Do put this file in .gitignore to ensure it doesn’t get tracked in case you’re planning to make your repository public.

Create a file called index.js where we’ll write all the necessary code(Yes, all the necessary code in one file, if you’re looking for prettier and more organized code, you can check out this repository and this file).

Paste the following code in the index.js file:-

The first 3 lines import the required dependencies and 5th line is importing the firebase.json file we earlier saved. We then initialize the Firebase admin with our credentials from the firebase.json file.

The tokens array will save the FCM tokens of users. FCM tokens can be thought of as device IDs; the push notification will be sent to the device associated with the FCM token.

We have 2 APIs, “/register” and “/notifications”.

Register API:-
This API will take the FCM Token of a user and push it into the tokens array. We’ll be looking at how to retrieve the FCM Tokens from a React Native application shortly. The tokens would ideally be saved into a database rather than an array, we’re using an array here for simplicity.

Notifications API:-
This API takes 3 parameters, title, body and imageUrl and send the push notification containing these parameters to the devices associated with the array of tokens we previously registered. We’ll use the admin.messaging().sendMulticast() function to send the notification to multiple devices.

Run

node index.js

to verify that the server starts perfectly.

Now let’s create the React Native application and set it up to receive push notifications. Make sure you have Run:-

npx react-native init pushNotificationsTest

Once the application is bootstrapped, connect your laptop to your phone via USB or an emulator and run

yarn start

and then

yarn android

to check whether the app is functioning properly. Ideally the app should start running on your phone/emulator and you should see the React Native introduction screen.

You’ll have to now set up a Firebase Cloud Messaging client app on your react native mobile app. To do so, head over to this link.

You have already completed the “Set up the SDK” and “Create a Firebase project” steps.
The next step involves registering your app with firebase, and you’ll find the package name of your app in android/app/build.grade under the android > defaultConfig section with the property name “applicationId”. If you used the same name as above, you should see something like this:-

defaultConfig {  applicationId "com.pushnotificationstest"  minSdkVersion rootProject.ext.minSdkVersion  targetSdkVersion rootProject.ext.targetSdkVersion  versionCode 1  versionName "1.0"}

Use this applicationId while registering your app with firebase following the instructions mentioned in the above link. Save the google-services.json file that gets downloaded under the android/app directory and follow the remaining steps under “Add a Firebase configuration file” section. When they refer to “root-level” or “project-level” directory, they mean the android directory and when the refer to “app-level” directory, they mean the android/app directory.

Once you’re done with the above step, follow the instructions under the “Add Firebase SDKs to your app” step as well. Make sure you’ve completed registration of your app with firebase in the previous step.

This should be the last step you follow from the above link. Do not go ahead with the “Edit your app manifest” step, it’s not required for our react native application.

Run the following command to install a few dependencies:-

yarn add @react-native-firebase/app @react-native-firebase/messaging axios

Restart your app once the dependencies are installed. Before we connect our backend with the mobile app, make sure your phone and laptop are running on the same network, for example, the same WiFi network. You’ll need this because you’ll be accessing the server that is running on your local system from an application that is not running on the same system.

Start the Node.js + Express server we earlier built by running:-

node index.js

Make sure your mobile app is running too, and paste the following code in the App.js file:-

The useEffect hook with an empty dependency array lets us execute a function once when the component mounts. We’re calling the sendFcmToken function, which firstly registers your device to receive remote messages(push notifications in our case) and then fetching the FCM token using the messaging().getToken() function. We’ll now have to make an API request to our server and we’ll use axios to do this. Replace the IP address “192.168.28.232” with the IP address being used by your system. You’ll generally find this under WiFi Settings.

And you’re done!

Let’s test it out. Don’t stop the app from the console, but close the app on your mobile. This is because you’ll be able to see push notifications only on the background, i.e., when the app is not running, and you’ll need additional setup to receive notifications to receive notifications on the foreground. You can refer to this documentation in case you want to do that.

So a couple of checks before you test it out:-

  1. Ensure your server is running on port 3000.
  2. Ensure your mobile app’s metro server is on but the app is closed on your mobile.

Now open the API tool of your choice, which is most likely Postman. I use an alternative, Insomnia, in case you want to check it out.

Now make a POST request to “http://192.168.29.241:3000/notifications” with the body:-

{
"title" : "Test Title",
"body": "Body of the test push notification"
}

You can also add an imageUrl property in case you want to send an image as well, but it’s completely optional.

And if you did everything right, you’ll have a notification like this one:-

Push Notification

And that’s it, you’re ready to send push notifications to the users of your app!

--

--