How to Set Up Push Notifications

Push notifications are key to marketing and a good user experience. In this tutorial, you'll learn how to implement push notifications using CometChat's UI kit.

Kevin Cunningham • Sep 6, 2022

Does using push notifications feel intimidating? When used well, push notifications are a low-effort tool that can enhance your marketing efforts and help keep your users up-to-date. Without needing to share an email address or other contact details, your users can receive targeted messages from you and your team instantly. After the user agrees, they can be invited back to your site for a sale, breaking news, or any other exciting piece of content you want to share. There are a number of studies that show a remarkable improvement in click-through rates for push notifications when compared to email.

In a related article, you learned how push notifications work and some push notifications best practices to employ when creating and sending push notifications. In this article, you'll learn how to use CometChat to set up your push notifications. CometChat helps removes the complexity regarding push notifications, letting you focus on creating your content and reaching users.

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/633efc917232059bf670058f_Blog_HowtoPushNotifications.png

Implementing Push Notifications with CometChat

To implement push notifications with CometChat, we need to use the CometChat UI kit. The CometChat UI kit handles the work of creating and maintaining a service worker, interacting with a real-time database, and managing your users:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/6315687f0f00584772d863a9_1URf97Z.png

In this tutorial, you'll set up a CometChat and Google Firebase account (if you don't have them already). In addition, you'll write some code to add push notifications to a plain HTML site. You can preview the final result in this GitHub repo.

Set Up Firebase

To begin, you need to set up an account with Firebase Cloud Messaging (FCM). FCM is a cross-platform messaging solution that allows you to send messages at no cost. CometChat uses this solution as the backend for its push notification service.

Navigate to the Firebase console and select Add project:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/6315687fe4e42a4b7571d8dd_iLLKJll.png

You'll need to give your project a name, decide on whether you'd like to activate analytics, and associate it with an account. You'll be able to track all our messages through CometChat, so it's not necessary to add another analytics layer here.

Once completed, Firebase will set everything up and let you know when it's ready:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156880e4e42a96e071d8ff_5uH7avl.png

Because a Firebase project can have multiple applications, you need to create a new app by clicking the web button highlighted here:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/631568804c4b6b04e7038d9a_2kE6zgi.png

You can name your app and register it on the next screen. In this tutorial, you'll only be using the cloud messaging solution, so when the registration screen offers hosting, say no. Once registered, select Continue, and you'll be taken back to the dashboard.

Gather Necessary Information

In order to configure push notifications, you need to gather two pieces of information: the FCM server key and the Firebase configuration code.

To obtain your server key, click the settings cog highlighted on the following picture on the Firebase dashboard:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/631568801ce61d5e0ce41530_hruPSbp.png

Then select Cloud Messaging at the top left of your screen:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156880e2280b217ef13b4f_x3gkTwn.png

The CometChat UI kit uses the Cloud Messaging API, which Google has marked as legacy. This is still fully functional and does everything you need it to, but needs to be enabled. Click the three dots to the right of the panel (as shown subsequently), and you'll be taken to the Google Cloud Console:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156880060cd4085700a512_ufPGYMy.png

Click ENABLE to enable the API:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156880032b0e0068490cad_S5oYti1.png

Refresh your Firebase project settings page, and you should see a server key:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/631568805ebb3c04c1a9874d_Jv6jT7k.png

This key lets CometChat use your Firebase instance and eliminate any possible push notification costs.

Now that you have your server key, you need to obtain the configuration object. Head over to the General tab under the Project settings tab, as shown here:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/631568801ce61da768e4157a_Z8JMekA.png

Scroll down to the SDK setup and configuration near the bottom of the code. Here, you'll see the firebaseConfig object being defined:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/631568811ce61d2207e4169e_R5Uimc7.png

Copy that, and you’ll have all the information you need from your Firebase console.

Please note: You should keep all these details private. The accounts used in this tutorial have been deleted prior to publication, which is why it's safe to share that information here.

Set Up CometChat

Now, it's time to head over to CometChat and sign up for an account. If this is your first time using CometChat, you'll be greeted with the Add New App modal as soon as you log in. Give your application a name and select the region closest to your users. Here's what the setup will look like:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156880e5625c6a03924a86_vF0Mbmw.png

Currently, there are two versions of the CometChat API. Version 2 is gradually being phased out, so it's best to choose version 3 for your application.

CometChat will create your application and take you back to the landing page. You can use CometChat to enhance your application in many ways, such as adding live chat or collaborative whiteboards. In this tutorial, you'll be focusing on push notifications; however, there is additional documentation available for other use cases.

In the CometChat dashboard, you need to enable the push notification Extensions. This extension will manage the communication between CometChat and FCM. To do this, click the Extensions tab in the left-hand navigation:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156881e34d8b3866183fe4_uYkG6cD.png

Scroll down to Push Notification and toggle the switch highlighted in the following image to enable it:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156881060cd42c7300a5e1_jQ4QZ59.png

Click on the cog below the toggle to pull up the settings; then scroll down to find the text area for the FCM Server key and paste the key you saved earlier:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/631568815ebb3c83a8a9877a_yXt3V4g.png

You can leave the rest of the settings for now, but feel free to explore them later. Scroll to the bottom of the modal and save your changes.

Now that you're done with the configuration, you can focus on writing code. You need all the details from this app during the next section, so make sure to keep this page open.

Integrate Your Application

In this section, you'll add push notifications to a plain HTML site, meaning you can focus on implementing push notifications without distractions. You could adapt this for any framework or library you're using with minimal changes.

In the <head> of your index.html, you need to import the relevant Firebase libraries and initialize your application. This will allow your website to interact with Firebase and pick up any messages that might be waiting for your user:

The CometChat.js file will import CometChat's UI kit:

This will allow your application to listen to events and be able to display notifications as they happen.

To display notifications when your user is not on the site, you need to add a service worker.

In the code above, you're checking if you can register a service worker and doing so when the window finishes loading. You'll notice this references another file that you'll create in a few moments named firebase-messaging-sw.js.

The final addition to the <head> of your HTML is the JavaScript for registering the client and the service worker. It's good practice to encapsulate this code in a separate file:

Create the Service Worker

Once registered, the service worker is going to listen for updates while your users are not on the site. This small file will run when the browser is open and will be responsible for triggering a notification when one is received.

Create a new file for your service worker named firebase-messaging-sw.js (the same name you registered previously).

This code will run separately from the main JavaScript thread as well as the DOM itself. You need to import your Firebase libraries as part of this script and reinitialize the application:

Once the service worker has initialized the application, you need to have Firebase listen for messages:

With that, your service worker is complete. This code will run in the background while the browser is open and display any notifications that are received.

Create the Client Code

The last file to create is the JavaScript file for the client application. Here, it's referred to as PushNotification.js.

There are three pieces of configuration you need from the CometChat dashboard. You can find them in the CometChat dashboard and add them to the top of our client code as shown here:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/6315688291ee61acef38699e_06Oy2VR.png

Add the global variables that you'll use throughout this code. Creating them on this level allows them to be updated and accessed by all the functions in this file:

In this tutorial, you're tying the logic of logging in and out to some HTML elements:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156881e5625c3ac3924acf_X3CVi0E.png

If you are using React or Vue, you may want to abstract this into a hook or a composable. You can also create and store a unique identifier rather than have a user provide a name. In either scenario, the flow of the code will be similar, with the try…catch being almost identical:

In the code above, you're connecting CometChat to the user through Firebase. The UID from the DOM and the AUTH_KEY from the constants are used for logging in the user to CometChat. At this point, Firebase messaging is activated and requests the token needed to talk to this user. Finally, the token is shared with CometChat, so it can target this particular user through Firebase.

If the user wants to stop receiving messages, you can provide logout capabilities as well, as seen here:

Test Your Notifications

When you create a CometChat application, some test users are provided for you:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156881032b0e4fbc490e44_QbWbous.png

In this example, the username "superhero1" has been used for logging in, but any other account could be used:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/6315688220f31621e2b7212e_OTc8ZVE.png

Your application is now ready to receive push notifications. You can test this by navigating away from this tab (but make sure it's still in the background) and sending a POST request to CometChat to tell it to create a new message. There are lots of tools available for this, like Postman, Insomnia, or curl on the command line.

You need to construct the URL, add the headers, and then create the body of your message.

The URL

The URL follows the following pattern: https://appId.api-region.cometchat.io/v3/messages. In this instance, using the details from the CometChat dashboard, this becomes https://21569492b2f3aa26.api-eu.cometchat.io/v3/users.

The Headers

There are three headers that you need to add to your request. The first two are universal, Content-Type and Accept, and both need to be set to application/json. The third header is the apiKey, which you need to get from the CometChat dashboard.

Select API & Auth Keys on the left-hand navigation, click on Rest API Keys, and copy the REST API key:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/631568820f0058b21ad8681d_SgRCW0C.png

Your completed headers should look like this:

https://uploads-ssl.webflow.com/5f3c19f18169b62a0d0bf387/63156882d45e6724cf8ef07e_VjCUqq5.png

The last thing you need is the payload, this is the actual message you will send.

The JSON Body

In the JSON body, you can set the category and type of your message, as well as who to send it to. Most importantly, you have the actual message content. Browsers vary on character limit here, so stick with a short message:

Send the request with your API tool, and you should see the notification pop up.

Conclusion

In this tutorial, you learned how to easily send push notifications using CometChat and Google Firebase. You created and registered a service worker and sent messages from your API client.

Adding push notifications to your website or app is easier than ever with CometChat -- we already did most of the work for you! Try CometChat today and see how quickly you can get a fully featured in-app messaging experience up and running.

Kevin Cunningham

CometChat

Kevin Cunningham is a developer and educator working with individuals and teams to level up their development skills. As a consultant, Kevin works with companies to ensure effective code architecture and developer practices. He specialises in helping teams migrate to new technology stacks. As a lifetime educator, Kevin loves to create learning experiences and does this regularly by teaching online and in-person. Away from the keyboard, you'll find Kevin walking, climbing and kayaking with his wife and kids.

Try out CometChat in action

Experience CometChat's messaging with this interactive demo built with CometChat's UI kits and SDKs.