Need help with React Native? Schedule a Free Consultation with our Experts.
Learn More

How to send push notifications in React native | Firebase

Send push notifications to specific devices in React Native (Android and ios) using firebase API. Firebase cloud messaging - Message types & Notifications.

Posted by Shashi on 20 Oct 2019
How to send push notifications in React native | Firebase

Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably deliver messages at no cost. FCM offers a broad range of messaging options and capabilities.Fcm is service that allows you to send notifications to your applications and receive information from them.

Message Types

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

  1. Notification messages, sometimes thought of as "display messages." These are handled by the FCM SDK automatically.
  2. Data messages, which are handled by the client app.

Notification messages

Notification messages, sometimes thought of as "display messages”. FCM automatically displays the message to end-user devices on behalf of the client app. Notification messages have a predefined set of user-visible keys and an optional data payload of custom key-value pairs.Use notification messages when you want FCM to handle displaying a notification on your client app's behalf.

Parameters

to (optional/string): This parameter specifies the recipient of a message.The value can be a device's registration token, a device group's notification key, or a single topic (prefixed with /topics/).

registration_ids (Optional, array of strings): This parameter specifies the recipient of a multicast message, a message sent to more than one registration token.

priority (Optional, string): Sets the priority of the message. Valid values are "normal" and "high." On iOS, these correspond to APNs priorities 5 and 10.

content_available (Optional, string): On iOS, use this field to represent content available in the APNs payload. When a notification or message is sent and this is set to true, an inactive client app is awoken, and the message is sent through APNs as a silent notification and not through the FCM connection server.

data (Optional, object): This parameter specifies the custom key-value pairs of the message's payload.For example, with data:{"score":"3x1"}:

For example, here is a JSON-formatted notification message. The user can expect to see a message with the title “Facebook” and the text "You have a new friend suggestion" on the device:

const message = {
   registration_ids: ["cWDVKttVMsA:APA91bFUlHrNqoIMdNE5_qWOADFue_tTzxWaRe_gWwoX28r2OKviHp4OZR0KsvpxPr_yARwbsnF-p69ao7lcZ0yz0JL74ZnwVzp8tXDDcqrHckIEhP2t2bC4Fg1-r1-xxxxxx_xxxxxx", "xxxxx...."],
    notification: {
      title: “Facebook”,
      body:”You have a new friend suggestion”,
      "vibrate": 1,
      "sound": 1,
      "show_in_foreground": true,
      "priority": "high",
      "content_available": true,
    },
}

Notification messages with optional data payload

FCM can send a notification message including an optional data payload. In such cases, FCM handles displaying the notification payload, and the client app handles the data payload.

const message = {
   registration_ids: ["cWDVKttVMsA:APA91bFUlHrNqoIMdNE5_qWOADFue_tTzxWaRe_gWwoX28r2OKviHp4OZR0KsvpxPr_xxxxx-p69ao7lcZ0yz0JL74ZnwVzp8tXDDcqrHckIEhP2t2bC4Fg1-x1-xxxxxx_xxxxxx", "xxxxx...."],
    notification: {
      Title:  “India vs south africa test",,
      Body: "IND chose to bat",
      "vibrate": 1,
      "sound": 1,
      "show_in_foreground": true,
      "priority": "high",
      "content_available": true,
    },
    data: {
      title: "india vs south africa test",
      body: "IND chose to bat",
      score: 199,
      wicket: 1
    }
}

Data Messages

Client app is responsible for processing data messages. Data messages have only custom key-value pairs. Set the appropriate key with your custom key-value pairs to send a data payload to the client app. For example, here is a JSON-formatted message, where the information is encapsulated in the common data key and the client app is expected to interpret the content.

const message = {
  title: "india vs south africa test",
  body: "IND chose to bat",
  score: 199,
  wicket: 1,
}

Send notification with REST API

notifications.js

export const sendPushNotification = async () => {
  const FIREBASE_API_KEY = "xxxxxxxxxxxxx"
  const message = {
    registration_ids: [
      "cWDVKttVMsA:APA91bFUlHrNqoIMdNE5_qWOADFue_tTzxWaRe_gWwoX28r2OKviHp4OZR0KsvpxPr_yARwbsnF-p69ao7lcZ0yz0JL74ZnwVzp8tXDDcqrHckIEhP2t2bC4Fg1-r1-xxxxxx_xxxxxx",
      "xxxxx....",
    ],
    notification: {
      title: "india vs south africa test",
      body: "IND chose to bat",
      vibrate: 1,
      sound: 1,
      show_in_foreground: true,
      priority: "high",
      content_available: true,
    },
    data: {
      title: "india vs south africa test",
      body: "IND chose to bat",
      score: 50,
      wicket: 1,
    },
  }

  let headers = new Headers({
    "Content-Type": "application/json",
    Authorization: "key=" + FIREBASE_API_KEY,
  })

  let response = await fetch("https://fcm.googleapis.com/fcm/send", {
    method: "POST",
    headers,
    body: JSON.stringify(message),
  })
  response = await response.json()
  console.log(response)
}

Note: In order to get notification when the app is killed, or in foreground, background use notification with data payload.

Obtaining fcm token or registration id

import firebase from "react-native-firebase"

export const getToken = async () => {
  let fcmToken = await AsyncStorage.getItem("fcmToken")
  console.log("fcmToken from AsyncStorage: ", fcmToken)
  if (!fcmToken) {
    fcmToken = await firebase.messaging().getToken()
    if (fcmToken) {
      console.log("fcmToken from firebase: ", fcmToken)
      await AsyncStorage.setItem("fcmToken", fcmToken)
    }
  }
  return fcmToken
}

To find your firebase API key

  1. Login to the Firebase Developer Console and go to your Dashboard.

  2. Click on the gear icon near project overview.

    Firebase dashboard

  3. Click on Project settings.

  4. Go to the “Cloud Messaging Section”.

  5. Legacy server key will be your firebase api key.

    Firebase API key



Shashi

Contact us to implement this for you.


Need help with React Native? Schedule a Free Consultation with our Experts.
Learn More

Related Services.



Hire ReactJS Developers
Hire Gatsby Developers
Hire NextJS Developers

We support the Open Source community.



Have a Project in mind?