React Native

Learn how to send push notifications for messages.

The Push Notification extension allows you to send push notifications to mobile apps and desktop browsers.

Add Push Notification

For React Native, there are numerous plugins available via NPM which can be used to set up push notifications for your apps like react-native-firebase, react-native-notifications and many more.

To setup Push Notification, you need to follow the steps mentioned in the Plugin's Documentation. You need to make different apps on the firebase console for each platform respectively (Android, iOS).

You can visit our Push Notification Setup guide to configure push notification in your react-native app using one of the above-mentioned packages.

  • To configure Firebase Push Notifications for your apps create a Firebase project at
    Firebase Console

Step 1: Add Firebase to your app

Create Firebase AppCreate Firebase App

Create Firebase App

If you have previously not created a Firebase project for your app Click Add project. If you already have created a project for your app in which you wish to integrate CometChat, select the same project, and download the config file:

  1. For Android, you need to download the google-services.json file.

  2. For iOS, you need to download the GoogleService-Info.plist file.

Step 2: Add FCM Server Key

  1. Login to the CometChat Dashboard.
  2. On the Extensions page add the Push Notifications extension.
  3. Go to the Installed tab and open the Settings for this extension.
  4. Enter the Title (usually name of the app) and FCM Server key.
  5. You can also toggle the triggers for sending Push Notifications. The triggers can be classified into 3 main categories:
    a. Message Notifications
    b. Call Notifications
    c. Group Notifications

Always get your Firebase Cloud Messaging Server Key from firebase console as shown below:

Subscribe To Topic/s

To subscribe to topics, you can either choose to use the subscribe to a topic method provided by the react-native-fireabase (messaging module) plugin, or you can use our APIs to subscribe to a topic.

For using the subscribe to a topic method provided by the Firebase, you can refer to the code snippet mentioned Push Notification Setup

If you wish to use our API, you can continue reading the documentation.

You can subscribe to topic/s in two ways:
a. Subscribe to all topics(all the joined groups and one-to-one conversations)
b. Subscribe to one topic.

a. Subscribe to all topics
If you wish to subscribe to all the groups you have previously joined, you can use the below code snippet.

📘

Note

You will still have to subscribe to groups individually whenever you join any group using the joinGroup() method provided by the SDK.

❗️

Please make sure you are subscribing to topics in the success of CometChat.login().

var appID = "APP_ID";
var token = "GENERATED_FCM_TOKEN";
var userUID = "UID_OF_LOGGED_IN_USER";
var appToken;
CometChat.getJoinedGroups().then(groups => {
  CometChat.getAppSettings().then(settings: any => {
    if(settings.extensions){
        settings.extensions.forEach(ext => {
            if (ext.id == "push-notification"){
            appToken = ext.appToken;
        }
        });
        }
    var url =
      "https://push-notification"+ region +".cometchat.io/v1/subscribetomany?appToken=" +
      appToken;
    fetch(url, {
      method: "POST",
      headers: new Headers({
        "Content-Type": "application/json"
      }),
      body: JSON.stringify({
        appId: appID,
        fcmToken: token,
        uid: userUID,
        groups: groups,
        platform: "reactnative"
      })
    })
      .then(response => {
        if (response.status < 200 || response.status >= 400) {
          console.log("Error subscribing to topics: " +response.status +" - " +response.text());
        } else {
          console.log("Subscribed to all topics");
        }
      })
      .catch(error => {
        console.error(error);
      });
  });
});

b. Subscribe to one topic:

To receive push notifications, the logged-in user must subscribe to two types of topics:

  1. Their own topic - All the messages for one-on-one conversations that are sent to the logged-in user are received using this topic. The topic you must subscribe to is AppID_user_UID where AppID is your CometChat App ID and UID is the logged-in user's ID.

🚧

Please note:

UID in case of users and GUID in case of groups are converted to lowercase by the Chat API. These are then used for generating the topic.

  1. Topics for all the groups the logged in user is a part of - All the messages for a group conversation are received using these topics. For every group joined, the logged-in user will have to subscribe to the topic for that group. For every group, you must subscribe to AppID_group_GUID where AppID is your CometChat App ID and GUID is the group's ID.

FCM topic messaging allows your app server to send a message to multiple devices that have opted into a particular topic. Based on the publish/subscribe model, topic messaging supports unlimited subscriptions per app.

var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings: any => {
    var appToken;
    if(settings.extensions){
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification"){
        appToken = ext.appToken;
      }
    });
    }
  var userType = "user";
  var UID = "UID";
  var appId = "APP_ID";
  var region = "REGION_OF_APP";
  var topic = appId + "_" + userType + "_" + UID;
  var url =
    "https://push-notification-"+ region +".cometchat.io/v1/subscribe?appToken=" +
    appToken +
    "";
  fetch(url, {
    method: "POST",
    headers: new Headers({
      "Content-Type": "application/json"
    }),
    body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
  })
    .then(response => {
      if (response.status < 200 || response.status >= 400) {
        console.log(
          "Error subscribing to topic: " +
            response.status +
            " - " +
            response.text()
        );
      }
      console.log('Subscribed to "' + topic + '"');
    })
    .catch(error => {
      console.error(error);
    });
});
var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings: any => {
  var appToken;
  if(settings.extensions){
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification"){
        appToken = ext.appToken;
      }
    });
    }
  var userType = "group";
  var GUID = "GUID";
  var appId = "APP_ID";
  var region = "REGION_OF_APP";
  var topic = appId + "_" + userType + "_" + GUID;
  var url =
    "https://push-notification-"+ region +".cometchat.io/v1/subscribe?appToken=" +
    appToken +
    "";
  fetch(url, {
    method: "POST",
    headers: new Headers({
      "Content-Type": "application/json"
    }),
    body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
  })
    .then(response => {
      if (response.status < 200 || response.status >= 400) {
        console.log(
          "Error subscribing to topic: " +
            response.status +
            " - " +
            response.text()
        );
      }

      console.log('Subscribed to "' + topic + '"');
    })
    .catch(error => {
      console.error(error);
    });
});

Unsubscribe From Topic/s

To unsubscribe from topics, you can either choose to use the unsubscribe from a topic method provided by the react-native-fireabase (messaging module) plugin, or you can use our APIs to subscribe to a topic.

For using the unsubscribe from a topic method provided by the Firebase, you can refer to the code snippet mentioned Push Notification Setup

If you wish to use our API, you can continue reading the documentation.

You can unsubscribe from topic/s in two ways:
a. Unsubscribe from all topics(all the joined groups and one-to-one conversations)
b. Unsubscribe from one topic.

a. Unsubscribe from all topics:
If you subscribe to all topics you can unsubscribe from all the topics you have subscribed to in your logout method using the below code snippet.

var appID =  "APP_ID";
var token = "GENERATED_FCM_TOKEN";
var appToken;
CometChat.getAppSettings().then(settings: any => {
  if(settings.extensions){
    settings.extensions.forEach(ext => {
        if (ext.id == "push-notification"){
        appToken = ext.appToken;
      }
    });
    }
  var url = "https://push-notification-"+ region +".cometchat.io/v1/unsubscribealltopic?appToken=" + appToken;
  fetch(
    url, 
    {
      method: "DELETE",
      headers: new Headers({
        "Content-Type": "application/json"
      }),
      body: JSON.stringify({ appId: appID, fcmToken: token })
    }
  )
  .then(response => {
    if (response.status < 200 || response.status >= 400) {
      console.log("Error unsubscribing from topics: " +response.status +" - " +response.text());
    } else {
      console.log("Unsubscribed from all topics"); 
    }
  })
  .catch(error => {
    console.error(error);
  });
});

b. Unsubscribe from one topic:
If you subscribe to a single topic you can unsubscribe from the single topic in the following way:

var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings: any => {
    var appToken;
    if(settings.extensions){
            settings.extensions.forEach(ext => {
            if (ext.id == "push-notification"){
            appToken = ext.appToken;
        }
        });
        }
    var userType = "user";
    var UID = "UID";
    var appId = "APP_ID";
    var region = "REGION_OF_APP";
    var topic = appId + "_" + userType + "_" + UID;
    var url =
    "https://push-notification-"+ region +".cometchat.io/v1/unsubscribe?appToken=" +
    appToken;
    fetch(url, 
        {
            method: "DELETE",
            headers: new Headers({
                "Content-Type": "application/json"
            }),
            body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
        }
    )
        .then(response => {
            if (response.status < 200 || response.status >= 400) {
            console.log(
                "Error subscribing to topic: " +
                response.status +
                " - " +
                response.text()
            );
            } else {
            console.log('Unsubscribed from "' + topic + '"');
            }
        })
        .catch(error => {
            console.error(error);
        });
    });
var token = "generated_FCM_token";
CometChat.getAppSettings().then(settings: any => {
    var appToken;
    if(settings.extensions){
        settings.extensions.forEach(ext => {
            if (ext.id == "push-notification"){
            appToken = ext.appToken;
        }
        });
        }
    var userType = "group";
    var GUID = "GUID";
    var appId = "APP_ID";
    var region = "REGION_OF_APP";
    var topic = appId + "_" + userType + "_" + GUID;
    var url =
    "https://push-notification-"+ region +".cometchat.io/v1/unsubscribe?appToken=" +
    appToken;
    fetch(url, 
        {
            method: "DELETE",
            headers: new Headers({
                "Content-Type": "application/json"
            }),
            body: JSON.stringify({ appId: appId, fcmToken: token, topic: topic })
        }
    )
        .then(response => {
            if (response.status < 200 || response.status >= 400) {
            console.log(
                "Error subscribing to topic: " +
                response.status +
                " - " +
                response.text()
            );
            } else {
            console.log('Unsubscribed from "' + topic + '"');
            }
        })
        .catch(error => {
            console.error(error);
        });
    });

Handle Custom Messages

To receive notification of CustomMessage, you need to set metadata while sending the CustomMessage.

var receiverID = "UID";
var customData = {
  latitude: "50.6192171633316",
  longitude: "-72.68182268750002"
};

var customType = "location";
var receiverType = CometChat.RECEIVER_TYPE.USER;
var metadata = {
  pushNotification: "Your Notification Message",
};

var customMessage = new CometChat.CustomMessage(
  receiverID,
  receiverType,
  customType,
  customData
);

customMessage.setMetadata(metadata);

CometChat.sendCustomMessage(customMessage).then(
  message => {
    // Message sent successfully.
    console.log("custom message sent successfully", message);
  },
  error => {
    console.log("custom message sending failed with error", error);
    // Handle exception.
  }
);

Converting push notification payload to message object

CometChat pro SDK provides a method CometChat.CometChatHelper.processMessage() to convert the message JSON to the corresponding object of TextMessage, MediaMessage,CustomMessage, Action or Call.

This code needs to be added to the onMessageReceived() method of the FirebaseMessagingService class.

var processedMessage = CometChat.CometChatHelper.processMessage(JSON_MESSAGE);

Messages

Simple text message

SenderName: text message

Attachment(s) with text

SenderName: text message

An attachment without text

SenderName: has sent you a/an Type

Attachments without text

SenderName: has sent you Types

📘

Type of Attachment can be of the following the type
1.CometChatConstants.MESSAGE_TYPE_IMAGE
2.CometChatConstants.MESSAGE_TYPE_VIDEO
3.CometChatConstants.MESSAGE_TYPE_AUDIO
4.CometChatConstants.MESSAGE_TYPE_FILE

Push Notification: Payload Sample for Text Message and Attachment/Media Message

{  
  "alert":"Spiderman: Text Message",
  "sound":"default",
  "title":"CometChat Pro",
  "message":{  
     "receiver":"superhero4",
     "data":{  
        "entities":{  
           "receiver":{  
              "entityType":"user",
              "entity":{  
                 "uid":"superhero4",
                 "role":"default",
                 "name":"Wolverine", 
                 "avatar":"http://data.cometchat.com/assets/images/avatars/wolverine.png",
                 "status":"offline"
              }
           },
           "sender":{  
              "entityType":"user",
              "entity":{  
                 "uid":"superhero3",
                 "role":"default",
                 "name":"Spiderman",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/spiderman.png",
                 "status":"offline"
              }
           }
        },
        "text":"Text Message"
     },
     "sender":"superhero3",
     "receiverType":"user",
     "id":"142",
     "sentAt":1555668711,
     "category":"message",
     "type":"text"
  }
}
{
  "alert":"Spiderman: has sent an image",
  "sound":"default",
  "title":"CometChat Pro",
  "message":{
     "receiver":"superhero4",
     "data":{
        "attachments":[
           {
              "extension":"png",
              "size":14327,
              "name":"extension_leftpanel.png",
              "mimeType":"image/png",
              "url":"https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
           }
        ],
        "entities":{
           "receiver":{
              "entityType":"user",
              "entity":{
                 "uid":"superhero4",
                 "role":"default",
                 "name":"Wolverine",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/wolverine.png",
                 "status":"offline"
              }
           },
           "sender":{
              "entityType":"user",
              "entity":{
                 "uid":"superhero3",
                 "role":"default",
                 "name":"Spiderman",
                 "avatar":"https://data.cometchat.com/assets/images/avatars/spiderman.png",
                 "status":"offline"
              }
           }
        },
        "url":"https://s3-eu-west-1.amazonaws.com/data.cometchat.com/1255466c41bd7f/media/1555671238_956450103_extension_leftpanel.png"
     },
     "sender":"superhero3",
     "receiverType":"user",
     "id":"145",
     "sentAt":1555671238,
     "category":"message",
     "type":"image"
  }
}

Did this page help you?