Integrate Push Notifications with Backend in React Native


Integrate Push Notifications with Backend in React Native
Integrate Push Notifications with Backend in React Native
Spread the love

Introduction

Push notifications on a mobile phone are an extremely fantastic app marketing strategy. They can be used everywhere, from news and messenger apps to fitness and health applications.

Yet it’s a waste if the user is not receiving these messages. But are you aware of the fact why?

Well, the fact that your customers are still not receiving messages might be because the procedure can be tricky. If this is the case, or if you just want to learn how to deal with push notifications in React Native, this article is for you.

We’d like to guide you through the process of integrating a Push Notification in React Native with backend services step by step.

During the process, you will develop a new React Native project to test on an Android smartphone, as well as a reduced version of the backend that enables delivering alerts to the device.  However, the idea is to give you the impression that implementing push notification systems is not difficult.

Now let’s get this process started!

A glimpse into Push Notifications

These are short pop-up messages that a user receives from the installed application’s developer. These pop-ups are also considered an excellent tool for increasing user engagement. Moreover, it has click rates that are 7 times higher than other mobile app marketing strategies.

However, notifications are widely used for a variety of reasons, including:

  • Allowing businesses to market items and services at a lower cost,
  • Enhancing the overall user experience
  • Transaction receipts are being sent out more quickly.
  • Increasing the number of users who convert
  • They are dependable; consumers always receive offline messages when they turn on their phones.

What are Backend Services in Push Notifications?

Some functions benefit from the interplay between a mobile application and an external data source. The back-end services deliver messages to devices that are running a mobile application.

See also  Experts believe India can beat China in wind energy component manufacturing

Well, there are numerous methods for setting up push notifications in React Native with backend services.

  • FCM/APNs are native platform-specific notification systems.
  • Showcase push alerts and other cloud services
  • Libraries for React Native, such as react native push notifications

Now let’s get started with the steps on how you can integrate push notifications with backend services in react native apps.

Steps to integrate Push Notifications with Backend Services in React Native

Step 1- Create a new React Native project

  • If you have all the requirements installed for creating React-native push notifications, use the following command to get the project started:

> npx react-native init notifications-test

  • Install the needed libraries as well. When you’ve finished creating the project, open it in your preferred editor (VS Code, Sublime) and modify the structure of the App.js file with the below command:

import React from ‘react’;

import {Button, SafeAreaView, StyleSheet, Text, View} from ‘react-native’;

const App = () => {

const handleSendNotification = () => {

  return;

};

const handleSetTheAlarm = () => {

  return;

};

return (

  <SafeAreaView style={styles.wrapper}>

    <Text>PUSH NOTIFICATIONS TEST</Text>

    <View style={styles.buttonsWrapper}>

      <View style={styles.buttonWrapper}>

        <Button title=”SEND NOTIFICATION” onPress={handleSendNotification} />

      </View>

      <View style={styles.buttonWrapper}>

        <Button

          title=”SET ALARM”

          color=”red”

          onPress={handleSetTheAlarm}

        />

      </View>

    </View>

  </SafeAreaView>

);

};

const styles = StyleSheet.create({

wrapper: {

  flex: 1,

  justifyContent: ‘center’,

  alignItems: ‘center’,

  padding: 20,

  backgroundColor: ‘white’,

},

buttonsWrapper: {

  marginTop: 50,

},

buttonWrapper: {

  marginBottom: 20,

},

});

export default App;

  • The application will then be launched. Moreover, the end result should look like this:

Step 2- Create a Backend Service Project

  • Create a project in the backend service. Then the next step is to include it in the React Native app.
  • The program will be tested on an Android smartphone; therefore, after selecting this type of application, go through all the procedures – some of them may require adjustments to the application code.
See also  We are proud to announce our new K cup filling machine.

Step 3- Creation of the Server Part

  • A new folder should be created in the selected place on the disk, e.g.,  “notifications-test-API”. Add the index.js file to it, where the code will be placed. The following commands will initiate a new node.js project and install all the necessary dependencies.

> npm init

> npm install fastify firebase-admin nodemon

  • For your backend service, you need to download serviceAccountKey, which must be added to the project folder.
  • In order to download this file, open the project settings, then in the Service accounts tab and select the Generate new private key button.
  • The following step is to copy and paste the code below into the index.js file, replacing the path to the previously downloaded file.

const admin = require(“firebase-admin”);

const fastify = require(“fastify”)({ logger: true, keepAliveTimeout: 5000 });

const util = require(“util”);

// Zastąp “path/to/serviceAccountKey.json”

const serviceAccount = require(“path/to/serviceAccountKey.json”);

const delay = util.promisify(setTimeout);

// Initialize Firebase

admin.initializeApp({

 credential: admin.credential.cert(serviceAccount),

});

// Remote Push Notification

async function sendAlarmNotification(token) {

 return admin.messaging().send({

   token,

   notification: {

     body: “Hi here’s your alarm”,

     title: “It’s time to wake up”,

   },

   data: {

     type: “alarmNotification”,

   },

 });

}

// Partial Push Notification

async function sendPartialNotification(token) {

 return admin.messaging().send({

   token,

   data: {

     type: “partial_notification”,

     notifee: JSON.stringify({

       body: “I’m your push notification”,

       android: {

         channelId: “default”,

       },

     }),

   },

 });

}

// Declare a notification route

fastify.post(“/notifications”, async (request) => {

 await delay(5000);

 await sendPartialNotification(JSON.parse(request.body).token);

 return “OK”;

});

// Declare a alarm route

fastify.post(“/alarm”, async (request) => {

 await delay(5000);

 await sendAlarmNotification(JSON.parse(request.body).token);

 return “OK”;

});

// Run the server

const start = async () => {

See also  China Parcel Tracking: A Critical Analysis

 try {

   await fastify.listen(3000);

 } catch (err) {

   fastify.log.error(err);

   process.exit(1);

 }

};

start();

  • We now have a functional server! It may be launched using the following command:
  • The function shown below is in charge of sending messages with the notification and data keys. Messages delivered in this format will result in Push Notifications being displayed on the device by the operating system.

// Remote Push Notification

async function sendAlarmNotification(token) {

 return admin.messaging().send({

   token,

   notification: {

     body: “Hi here’s your alarm”,

     title: “It’s time to wake up”,

   },

   data: {

     type: “alarmNotification”,

   },

 });

}

  • In the latter situation, the message will be only delivered with the data key. Moreover, such a notice won’t be shown on demand. To display such a notice, we must first develop the logic that would handle it.

Step 4- Display and support Remote Push Notifications on the device

The final step is to add push notification support to the React Native application, i.e.

  • Registration of a device in Cloud Messaging
  • download of a registered token
  • As a convenience, we will include the token in every query to the server; this is necessary for the server to identify the receivers of Push Notifications (in a real project, I suggest that it be kept, e.g. in the database).

The following code should be added to App.js, fulfilling these assumptions.

const [token, setToken] = useState(”);

 const getFirebaseToken = async () => {

   // Register the device with FCM

   await messaging().registerDeviceForRemoteMessages();

   // Get the token

   const generatedToken = await messaging().getToken();

   return generatedToken;

 };

 useEffect(() => {

   async function fetchData() {

     const generatedToken = await getFirebaseToken();

     setToken(generatedToken);

   }

   fetchData();

 }, []);

Conclusion

Overall, we hope you found our tutorial on integrating push notifications with backend services in push notifications beneficial. But, if you are searching for a supplier to incorporate these notifications in react native apps, WonderPush is a fantastic solution. It is the least priced and most practical. So choose it and let your React NativePush Notifications speak.


Spread the love

Adil Husnain

Adil Husnain is a well-known name in the blogging and SEO industry. He is known for his extensive knowledge and expertise in the field, and has helped numerous businesses and individuals to improve their online visibility and traffic.