Chat SDKs JavaScript v3
Chat SDKs JavaScript
Chat SDKs
JavaScript
Version 3
Sendbird Chat SDK v3 for JavaScript is no longer supported as a new version is released. Check out our latest Chat SDK v4

Push notifications

Copy link

Using our Chat SDK for JavaScript, you can send notifications to your hybrid mobile application users. These notifications are delivered to users while their devices are idle or while the app is running in the background. You can also show the content of the notifications to your app while it is in the foreground.

Currently, only a hybrid mobile application with a React Native framework can handle push notifications with our Chat SDK. This page explains how to enable push notifications in your React Native app by using Firebase Cloud Messaging (FCM), Apple Push Notification service (APNs), and the Chat SDK.

Note: The Chat SDK doesn't support push notifications in web applications delivered through browsers like Chrome and Edge. But you can build your own notification system by using our webhook service to receive notifications for various events happening in your application.

While the Chat SDKs for iOS and Android automatically detect the state of your application, the Chat SDK for JavaScript doesn't. Therefore when the state changes, you should explicitly call the setForegroundState() or setBackgroundState() method.

The following steps in this page are written with the assumption that you have already registered the certificates and credentials of FCM and APNs to the Sendbird server via your dashboard or by using the platform API's related actions.

Note: Push notifications are only supported in group channels.


Step 1: Install libraries and configure FCM and APNs

Copy link

The @react-native-firebase/app library is an easy-to-use FCM library for simple integration. You can configure FCM for your React Native project by following the instructions in the Notifications page from the React Native Firebase documentation.

$ npm install @react-native-firebase/app @react-native-firebase/messaging

Note: As the Google Cloud Messaging (GCM) server and client APIs are deprecated and removed as of April 11, 2019, we recommend that you use FCM and develop push notifications with the @react-native-firebase/app library for your project.

To receive push notifications on iOS devices, you can integrate APNs by installing the @react-native-community/push-notification-ios library. For more details, see the Install section of the library's documentation.

$ npm install @react-native-community/push-notification-ios

Step 2: Register tokens for FCM and APNs to the Sendbird server

Copy link

Note: A user can have up to 20 FCM registration tokens and 20 APNs device tokens each. The oldest token will be deleted before a new token is added for a user who already has 20 registration or device tokens. Only the 20 newest tokens will be maintained for users who already have more than 20 of each token type.

The FCM server requires an FCM registration token and an APNs device token for client app instances when targeting a particular device to send a push notification. The Chat SDK provides an interface to register and unregister two types of tokens to the Sendbird server. The tokens are used to communicate with the FCM server. The following is an example of the registration in our React Native sample.

import messaging from '@react-native-firebase/messaging';

const sb = SendBird.getInstance();

if (Platform.OS === 'ios') {
    const token = await messaging().getAPNSToken();
    try {
        const response = await sb.registerAPNSPushTokenForCurrentUser(token);
        // Do something in response to a successful registration.
    } catch (error) {
        // Handle error.
    }
} else {
    const token = await messaging().getToken();
    try {
        const response = await sb.registerGCMPushTokenForCurrentUser(token);
        // Do something in response to a successful registration.
    } catch (error) {
        // Handle error.
    }
}

Step 3: Receive notification messages

Copy link

Once the token is registered, Android client apps receive notification messages via FCM, and iOS client apps via APNs.

While APNs requires no further configuration in receiving these messages, FCM requires the client app instance to receive and handle FCM notification messages. Instructions on the Receiving Messages section show you how to receive FCM messages based on the client app's state, which can be foreground, background, or quit.

The sample code below shows how to parse received FCM messages and display the messages using local notifications while the client app is in the background or quit state.

Note: For Android 8.0 (API level 26) and higher, all notifications must be assigned to a notification channel, so you should provide a Notification instance with the required data such as the ID of a notification channel.

import messaging from '@react-native-firebase/messaging';
import notifee, { AndroidImportance } from '@notifee/react-native';

// Link: https://rnfirebase.io/messaging/usage#background--quit-state-messages
messaging().setBackgroundMessageHandler(async (message) => {
    const isSendbirdNotification = Boolean(message.data.sendbird);
    if(!isSendbirdNotification) return;

    const text = message.data.message;
    const payload = JSON.parse(message.data.sendbird);

    // The following is required for compatibility with Android 8.0 (API level 26) and higher.
    // Link: https://notifee.app/react-native/reference/createchannel
    // Link: https://notifee.app/react-native/reference/androidchannel
    const channelId = await notifee.createChannel({
        id: 'NOTIFICATION_CHANNEL_ID',
        name: 'NOTIFICATION_CHANNEL_NAME',
        importance: AndroidImportance.HIGH
    });

    // Link: https://notifee.app/react-native/reference/displaynotification
    await notifee.displayNotification({
        id: message.messageId,
        title: 'New message has arrived!',
        subtitle: `Number of unread messages: ${payload.unread_message_count}`,
        body: payload.message,
        data: payload,
        // Link: https://notifee.app/react-native/reference/notificationandroid
        android: {
            channelId,
            smallIcon: NOTIFICATION_ICON_RESOURCE_ID,
            importance: AndroidImportance.HIGH,
        },
        // Link: https://notifee.app/react-native/reference/notificationios
        ios: {
            foregroundPresentationOptions: {
                alert: true,
                badge: true,
                sound: true,
            },
        },
    });
})

Additionally, the sample code below shows how to handle local notifications in Android and iOS. Refer to the event sections of the Notifee and push-notification-ios libraries to learn more.

import Notifee, { EventType } from '@notifee/react-native';
import PushNotificationIOS from '@react-native-community/push-notification-ios';

// Handle data from '@react-native-community/push-notification-ios'
const onNotificationIOS = (notification) => {
    const data = notification?.getData();
    if (data && data.userInteraction === 1 && Boolean(data.sendbird)) {
        // navigate to channel
        // const channelUrl = data.sendbird.channel.channel_url;
    }
}

// Handle data from '@notifee/react-native'
const onNotificationAndroid = async (event) => {
    if(event.type === EventType.PRESS && Boolean(event.detail.notification?.data?.sendbird)) {
        // navigate to channel
        // const channelUrl = event.detail.notification.data.sendbird.channel.channel_url;
    }
}

const App = () => {
    useEffect(() => {
        PushNotificationIOS.getInitialNotification().then(onNotificationIOS);
        PushNotificationIOS.addEventListener('localNotification', onNotificationIOS);
        const unsubscribe = Notifee.onForegroundEvent(onNotificationAndroid);
        return () => {
            PushNotificationIOS.removeEventListener('localNotification');
            unsubscribe();
        }
    },[])

    // ...
    // Your app
}

Notifee.onBackgroundEvent(onNotificationAndroid)

The data above, which is parsed from an FCM data message, contains a set of key-value items shown in the below JSON format. The data has a full set of information about the push notification. For example, the value of the message key means a received text message. As for the channel_unread_count, the attribute can be added into or removed from the payload in Settings > Application > Notifications on Sendbird Dashboard.

{
    "category": "messaging:offline_notification",
    "type": string,                 // Message type: 'MESG', 'FILE', or 'ADMM'
    "message": string,              // User input message
    "custom_type": string,          // Custom message type
    "message_id": long,             // Message ID
    "created_at": long,             // The time that the message was created, in a 13-digit Unix milliseconds format
    "app_id": string,               // Application's unique ID
    "unread_message_count": int,    // Total number of new messages unread by the user
    "channel": {
        "channel_url": string,      // Group channel URL
        "name": string,             // Group channel name
        "custom_type": string,       // Custom Group channel type
        "channel_unread_count": int // Total number of unread new messages from the specific channel
    },
    "channel_type": string,         // The value of "channel_type" is set by the system. The 'messaging' indicates a distinct group channel while 'group_messaging' indicates a private group channel and 'chat' indicates all other cases.
    "sender": {
        "id": string,               // Sender's unique ID
        "name": string,             // Sender's nickname
        "profile_url": string,       // Sender's profile image URL
        "require_auth_for_profile_image": false,
        "metadata": {}
    },
    "recipient": {
        "id": string,               // Recipient's unique ID
        "name": string              // Recipient's nickname
    },
    "files": [],                    // An array of data regarding the file message, such as filename
    "translations": {},             // The items of locale:translation.
    "push_title": string,           // Title of a notification message that can be customized in the Sendbird Dashboard with or without variables
    "push_sound": string,           // The location of a sound file for notifications
    "audience_type": string,        // The type of audiences for notifications
    "mentioned_users": {
        "user_id": string,          // The ID of a mentioned user
        "nickname": string,         // The nickname of a mentioned user
        "profile_url": string,      // Mentioned user's profile image URL
        "require_auth_for_profile_image": false
    },
}

Notification preferences

Copy link

By registering or unregistering the current user's registration token to the Sendbird server as below, you can turn push notifications on or off in the user's app.

Note: The registration and unregistration methods in the code below should be called after a user has established a connection with the Sendbird server via the connect() method.

const sb = SendBird.getInstance();

function setPushNotification(enable, os) {
    if (enable) {
        if (os === 'ios') {
            try {
                const response = await sb.registerAPNSPushTokenForCurrentUser(TOKEN);
                // Do something in response to a successful registration.
            } catch (error) {
                // Handle error.
            }
        } else {
            try {
                const response = await sb.registerGCMPushTokenForCurrentUser(TOKEN);
                // Do something in response to a successful registration.
            } catch (error) {
                // Handle error.
            }
        }
    } else {
        if (os === 'ios') {
            try {
                const response = await sb.unregisterAPNSPushTokenForCurrentUser(TOKEN);
                // Do something in response to a successful unregistration.
            } catch (error) {
                // Handle error.
            }
        } else {
            try {
                const response = await sb.unregisterGCMPushTokenForCurrentUser(TOKEN);
                // Do something in response to a successful unregistration.
            } catch (error) {
                // Handle error.
            }
        }
    }
}

Push trigger options allow users to configure when to receive notification messages as well as what type of messages will trigger notification messages. The following three options are provided:

List of push trigger options

Copy link
OptionDescription

all

When disconnected from the Sendbird server, the current user receives notifications for all new messages including messages the user has been mentioned in.

mention_only

When disconnected from the Sendbird server, the current user only receives notifications for messages the user has been mentioned in.

off

The current user doesn't receive any notifications.

const sb = SendBird.getInstance();

// If you want to trigger notification messages only when the current user is mentioned in messages.
try {
    const response = await sb.setPushTriggerOption('mention_only');
    // Do something in response to setting.
} catch (error) {
    // Handle error.
}

Push trigger options for channel also allow users to configure the trigger for notification messages as well as turn notifications on or off for each channel. The following four options are provided:

List of push trigger options for channel

Copy link
OptionDescription

default

The current user’s push notification trigger settings are automatically applied to the channel. This is the default setting.

all

When disconnected from the Sendbird server, the current user receives notifications for all new messages in the channel including messages the user has been mentioned in.

mention_only

When disconnected from the Sendbird server, the current user only receives notifications for messages in the channel the user has been mentioned in.

off

The current user doesn't receive any notifications in the channel.

// If you want to automatically apply the user's push notification setting to the channel.
try {
    const response = await groupChannel.setMyPushTriggerOption('default');
    // Do something in response to setting.
} catch (error) {
    // Handle error.
}

If you want to routinely turn off push notification on the current user's client app according to a specified schedule, use our Do Not Disturb feature like the following.

Note: Do Not Disturb can also be set for a user with our platform API's update push notification preferences action.

const sb = SendBird.getInstance();

// The current user will not receive push notifications during the specified time of every day.
try {
    const response = await sb.setDoNotDisturb(true, START_HOUR, START_MIN, END_HOUR, END_MIN, 'Asia/Seoul');
    // Do something in response to setting.
} catch (error) {
    // Handle error.
}

To snooze notification messages for a specific period of time, use our snooze feature like the following.

Note: snooze can also be set for a user with our platform API's update push notification preferences action.

const sb = SendBird.getInstance();

// The current user will not receive notification messages during the specified period of time (from START_TS to END_TS).
try {
    const response = await sb.setSnoozePeriod(true, START_TS, END_TS);
    // Do something in response to setting.
} catch (error) {
    // Handle error.
}

Push notification content templates

Copy link

Push notification content templates are pre-formatted forms that can be customized to display your own push notification messages on a user’s device. Sendbird provides two types: default and alternative. Both templates can be customized from your dashboard by going to Settings > Chat > Notifications > Push notification content templates.

Content templates

Copy link

There are two types of push notification content template: Default and Alternative. Default template is a template that applies to users with the initial notification message setting. Alternative template is used when a user selects a different notification content template instead of the default template.

The content in the template is set at the application level while the selection of templates is determined by a user or through the Platform API.

Note: When a custom channel type has its own customized push notification content template, it takes precedence over the default or alternative templates.

Both templates can be customized using the variables of sender_name, filename, message, channel_name, and file_type_friendly which will be replaced with the corresponding string values. As for the file_type_friendly, it will indicate the type of the file sent, such as Audio, Image, and Video.


Refer to the following table for the usage of content templates:

Content templates use cases

Copy link
Text messageFile message

Default template

{sender_name}: {message} (ex. Cindy: Hi!)

{filename} (ex. hello_world.jpg)

Alternative template

New message arrived

New file arrived

To apply a template to push notifications, use the setPushTemplate() method. Specify the template name as either with PUSH_TEMPLATE_DEFAULT or PUSH_TEMPLATE_ALTERNATIVE.

const sb = SendBird.getInstance();

try {
    const response = await sb.setPushTemplate(sb.PUSH_TEMPLATE_ALTERNATIVE);
    // Push template successfully set to 'PUSH_TEMPLATE_ALTERNATIVE'.
} catch (error) {
    // Handle error.
}

To check the current user's push notification template, use the getPushTemplate() method like the following:

const sb = SendBird.getInstance();

try {
    const pushTemplate = await sb.getPushTemplate();
    if (pushTemplate == sb.PUSH_TEMPLATE_DEFAULT) {
        // Currently configured to use the default template.
    } else if (pushTemplate == sb.PUSH_TEMPLATE_ALTERNATIVE) {
        // Currently configured to use the alternative template.
    }
} catch (error) {
    // Handle error.
}

Push notification translation

Copy link

Push notification translation allows your users to receive notification messages in their preferred languages. Users can set up to four preferred languages. If messages are sent in one of those languages, the notification messages won’t be translated. If messages are sent in a language other than the preferred languages, the notification messages will be translated into the user's first preferred language. In addition, the messages translated into other preferred languages will be provided in the sendbird property of a notification message payload.

Note: A specific user's preferred languages can be set with our platform API's update a user action.

The current user's preferred languages can be set using the updateCurrentUserInfoWithPreferredLanguages() method as follows:

const sb = SendBird.getInstance();
const preferredLanguages = ['fr', 'de', 'es', 'ko'];    // French, German, Spanish, and Korean

try {
    let isUpdatedSuccessfully = true;

    for (let language of sb.currentUser.preferredLanguages) {   // The sb.currentUser.preferredLanguages returns a list of the current user's preferred languages.
        if (!preferredLanguages.inlcudes(language)) {
            isUpdatedSuccessfully = false;
            break;
        }
    }

    if (isUpdatedSuccessfully) {
        // The current user's preferred languages have been updated successfully.
    }
} catch (error) {
    // Handle error.
}

If successful, the following notification message payload will be delivered to the current user's device.

{
    "message": {
        "token": "ad3nNwPe3H0:ZI3k_HHwgRpoDKCIZvvRMExUdFQ3P1...",
        "notification": {
            "title": "Greeting!",
            "body": "Bonjour comment allez vous"    // A notification message is translated into the first language listed in the preferred languages.
        }
    },
    "sendbird": {
        "category": "messaging:offline_notification",
        "type": "User",
        "message": "Hello, how are you?",
        ...

        "translations": {   // The translated messages in other preferred languages.
            "fr": "Bonjour comment allez vous",
            "de": "Hallo wie geht es dir",
            "es": "Hola como estas",
            "kr": "안녕하십니까?"
        },

        ...
    }
}