Fortune Ikechi Fortune Ikechi is a Frontend Engineer based in Rivers State Nigeria. He is a student of the University of Port-Harcourt. He is passionate about community and software engineering processes.

How to create and send push notifications in React Native

5 min read 1534

React Native Push Notifications Using Expo

Push notifications — messages from apps that are sent to users who have installed the app — have become an important aspect to consider when building applications for businesses and users.

They are similar to SMS messages, but don’t cost anything to send. As a result, many businesses now prefer push notifications to send out information and alerts to users who have their apps installed. In this article, we’ll take a look at push notifications in React Native.

What are push notifications?

Push notifications are messages or alerts sent by the makers of an application the user has installed. There are two main types of notifications, namely foreground and background notifications.

A foreground notification is a notification type that the user gets when the app is currently open and running, while background notifications are sent whether or not the app is currently open.

Push notifications are popular in the world of mobile app development for a number of reasons, including:

  • They enable firms to advertise products and offers at a reduced cost
  • They improve overall user experience
  • They aid in the sending of transaction receipts faster
  • They are used to convert more users

Push notification architecture in React Native

Push notifications in React Native APN FCM
Push notification architecture in React Native

When it comes to push notifications in React Native, there are three ways to set up push notifications:

  • Apple Push Notification service (APN)
  • Expo Push Notification service
  • Firebase Cloud Messaging (FCM)

APNs are used as a cloud service by Apple for iOS notifications, and you’ll need to register your app in order to get access to one. One of the benefits of APN is that it allows you to send notifications to the user without knowing their respective IP addresses.

FCM is provided by Google and can be incorporated into your backend system or used independently. With APNs and an FCM, the developer only gets the device token from the devices, while these cloud services focus on sending push messages to the users device.

Expo Push Notification services are provided by Expo and React Native, which works for free and for Expo-managed React Native applications like the one we will be using for this tutorial.

To use push notifications in a React Native application, first we need to register the app to get a push notification token. This token is a long string that uniquely identifies each device. Then, we’ll store the token in a database on the server, send a notification, and handle the received notifications we’ve sent.

We made a custom demo for .
No really. Click here to check it out.

Setting up your project

Before we dive in too deep, we are going to add push notifications to a project that’s already initialized. This project is an ecommerce React Native application for selling used items. To initialize it locally, run the following command in your terminal:

git clone https://github.com/iamfortune/Done-With-It-App.git

Next, we’ll install the dependencies needed for the project and start our server:

yarn install 
yarn start 

This initializes a React Native project that can be viewed on Android Studio using an emulator or on your own device using Expo. Next, we’ll get a push notification token from React Native Expo.

Getting a push notification token

To use push notifications in a React Native application, first we need to register the app to get a push notification token. Here, we will be using the notifications API in Expo.

To do this, let’s cd into the Navigation directory and the AppNavigator component. Here we are going to derive a token from Expo. Let’s get the Notifications and Permissions functions from Expo below:

import { Notifications } from 'expo';
import * as Permissions from 'expo-permissions';

The above functions help us request user permissions to send a push notification. Now, we will write an async function in the AppNavigator component that will request a token from React Native Expo:

 const registerForPushNotifications = async () => { 
    try {
       const permission = await Permissions.askAsync(Permissions.NOTIFICATIONS);
       if (!permission.granted) return;
       const token = await Notifications.getExpoPushTokenAsync();
    console.log(token);
    } catch (error) {
      console.log('Error getting a token', error);
    }
  }

In the code above, we are using the Permissions module that we recently installed to get the user’s permission on notifications. The function waits to receive the permissions object. Next, we check to see if the permission is granted, and if it’s not, we return immediately.

To get the token, we await a call to notifications functions to get the Expo push notifications token and log the token on the console for now. In order to catch possible errors, we wrap the code in a try catch block.

To call the above function for our application, we are going to use the useEffect hook from React:

const AppNavigator = () => {
  useEffect(() => {
    registerForPushNotifications();
  }, [])

In the code above, we passed the useEffect hook that we imported from react and passed a function registerForPushNotifications to make sure it’s only called once. We also added the empty braces so that when viewed on a device, the Expo push token will be displayed.

Storing a push notification token in a project

In order to store and use a push notification from our server, we need to configure our application user interface in a way that it is able to register new users and devices. To achieve this, let’s go to our api directory in our project and open a new file that we will call expoPushTokens.js. Then do the following:

import client from './client';
const register = (pushToken) => client.post('/expoPushTokens', { token: pushToken });
export default {
    register,
}

In the code above, we are first importing the client module, which is also in the api directory.

We define a function register that takes a pushToken. Now we’ll post a client or new user to the url that’s on the backend /expoPushToken. In the body of the request, we’re going to add an object token that is set to pushToken. Then, we’ll export as a default object with a register method.

Next, we return to the AppNavigator component, and, instead of logging our token on the console, we will send it to the server.

import expoPushTokensApi from '../api/expoPushTokens';

 const registerForPushNotifications = async () => { 
   ///
       const token = await Notifications.getExpoPushTokenAsync();
  expoPushTokensApi.register(token)
    } catch (error) {
      console.log('Error getting a token', error);
    }
  }

Now, we are sending the new user to get a token and the user info.

Sending test notifications

To send test notifications in React Native using Expo, first head over to the expo notifications documentation and fill out the required form. However, to ensure you receive your notifications, you’d have to write the following when setting the Data (JSON) in the form:

{*_displayInForeground*: true}

This lets React Native know to send the notification when the app is in foreground.

Sending notifications on the server

To send push notifications to the server, we need to use one of the SDKs provided by Expo. If you visit the documentation, it provides us with information on how to implement push notifications on the server in many languages.

In this tutorial, I’ll be working with a NodeJS server. Here is a link to the server I’ve used for this tutorial. We’ll visit the utilities directory in the server and include the Expo SDK on it. To do this, we first do the following:

git clone https://github.com/iamfortune/DoneWithIt-Backend

Next we install the npm packages using the command:

npm install 

Then we start our development server with:

npm start 

Now, go to the pushNotifications.js file and add the Expo SDK to the packages.

npm i expo-server-sdk
const { Expo } = require("expo-server-sdk");

Next, we’ll write a function that will receive our push notifications — both the push tokens and the message we want to send the user. Then, we’ll create a new chunk method to handle the push notifications.

const sendPushNotification = async (targetExpoPushToken, message) => {
  const expo = new Expo();
  const chunks = expo.chunkPushNotifications([
    { to: targetExpoPushToken, sound: "default", body: message }
  ]);

Next, let’s determine how to handle notifications we’ve received.

Handling received notifications in React Native

To handle received notifications, first we need to have an event listener that will be called every time the user clicks on a notification. Let’s add an event listener inside of our AppNavigator function that takes in the notification object:

 const AppNavigator = () => {
  useEffect(() => {
    registerForPushNotifications();

    Notifications.addListener(notification => console.log(notification))
  }, [])

Next, we’ll send notifications using the expo notifications on our browser (we should be able to see the notifications on our browser). Now’ll we’ll need to see the notifications sent by setting the listeners to receive the notifications:

const useNotifications = (notificationListener) => {
  useEffect(() => {
    registerForPushNotifications();

    if (notificationListener) Notifications.addListener(notificationListener);
  }, []);

Here, we are saying if the notifications listener gets a new notification, it should display it to user.

Conclusion

In this article, we’ve seen why push notifications are popular and here to stay in the application world, and we’ve learned how to send push notifications in React Native applications by adding notification tokens, sending them from the server, and displaying them on user devices.

You can read more in the Expo documentations and React Native docs.

Fortune Ikechi Fortune Ikechi is a Frontend Engineer based in Rivers State Nigeria. He is a student of the University of Port-Harcourt. He is passionate about community and software engineering processes.

Leave a Reply