Menu

Rate this page:

Thanks for rating this page!

We are always striving to improve our documentation quality, and your feedback is valuable to us. How could this documentation serve you better?

Push Notifications on Web

Push Notifications on Web

Push notifications are an important part of the web experience. Users have grown accustomed to having push notifications be a part of virtually every app that they use. The JavaScript Programmable Chat SDK is built to have FCM push notifications integrated into it. Managing your push credentials is necessary as your registration token is required for the Chat SDK to be able to send any notifications through FCM. Let's go through the process of managing your push credentials.

Step 1 - Enable push notifications for your Service instance

IMPORTANT: The default enabled flag for new Service instances for all Push Notifications is false. This means that Push will be disabled until you explicitly enable it. Follow this guide to do so.

Step 2 - Configure Firebase

FCM need configuration provided by developer to notifications configured. Google provides an easy-to-use Firebase Console to manager Firebase services and configurations.

Create a project on Firebase

To use push notifications for your Android apps, you will need to create a project on the Firebase Console:

Create A Firebase Project

Get project's configuration

The Firebase Cloud Messaging (FCM) requires configuration to initialize. The Firebase console has an easy way to generate this configuration.

After you create a Firebase project, you can select option to add Firebase to your web app:

Get Started With Firebase

Clicking the right link will bring up this dialog:

AddFirebaseToYourWebApp.width-500

This dialog contains sample JavaScript code with filled in parameters for your created project ready to use in web app.

Save this sample code with configuration - we will use it later in this guide.

Step 3 - Upload your API Key to Twilio

Now that we have our app configured to receive push notifications let's upload our API Key by creating a Credential resource. Check out this page to generate a credential SID using the API key.

API Key

Step 4 - Pass the API Credential Sid in your Access Token

This step is to ensure that your Chat JS SDK client Access Token includes the correct credential_sid - the one you created in Step 3 above. Each of the Twilio Helper Libraries enables you to add the push_credential_sid. Please see the relevant documentation for your preferred Helper Library for the details. Here is an example using the Node.js Twilio helper Library:

var chatGrant = new ChatGrant({
    serviceSid: ChatServicesSid,
    pushCredentialSid: FCM_Credential_Sid,
});

Step 5 - Initializing Firebase in your web app

Now it's time to initialize the Firebase with sample code we got in Step 2.

Somewhere in your web app early initialization sequence call the sample code (and do not forget to include/import firebase library provided by Google). We recommend to add additional check for correct import of firebase libraries.

  // Initialize Firebase
  var config = {
    apiKey: "...",
    authDomain: "...",
    databaseURL: "...",
    projectId: "...",
    storageBucket: "...",
    messagingSenderId: "..."
  };
  if (firebase) {
    firebase.initializeApp(config);
  }

Step 6 - Requesting push permissions from user and getting FCM token

In this step we are requesting permissions from user to subscribe to and display notifications. Again, we are recommending to add additional checks for firebase correct initialization

 if (firebase && firebase.messaging()) {
      // requesting permission to use push notifications
      firebase.messaging().requestPermission().then(() => {
        // getting FCM token
        firebase.messaging().getToken().then((fcmToken) => {
          // continue with Step 7 here 
          // ... 
          // ... 
        }).catch((err) => {
          // can't get token
        });
      }).catch((err) => {
        // can't request permission or permission hasn't been granted to the web app by the user
      });
    } else {
      // no Firebase library imported or Firebase library wasn't correctly initialized
    }

Step 7 - Passing FCM token to Chat JS SDK and registering event listener for new push arrival

If you got to this step, then you have Firebase correctly configured and FCM token ready to be registered with Chat SDK. This step assumes that you have Chat Client created with correct Access Token from Step 4.

// passing FCM token to the `chatClientInstance` to register for push notifications
chatClientInstance.setPushRegistrationId('fcm', fcmToken);

// registering event listener on new message from firebase to pass it to the Chat SDK for parsing
firebase.messaging().onMessage(payload => {
    chatClientInstance.handlePushNotification(payload);
});

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.

Loading Code Sample...