Web Push Notifications

Web push notification is an important feature for any web application. Along with Email, you should send important account related events to your users via Web Push channel. In this article, we’ll learn how to add Web Push Notifications to a React app using Engagespot.

Create Your React App

If you already have a ReactJS app, feel free to skip this section. Otherwise, you can create a new React app as follows

npx create-react-app engagespot-react
cd engagespot-react

Get a FREE Engagespot API Key

Login to your Engagespot account (or create one if you donot have one). And you can see your Engagespot API Key. (Do not confuse with ENGAGESPOT_API_SECRET). Copy your API Key.

Add Service Worker to Your React App.

To enable web push, you should setup service worker in your React App. Don’t worry. It’s a simple process. Let’s do it.

Create a service-worker.js file in your React app’s public folder. service-worker file

Add the following text to the service-worker.js file and save it.

importScripts('https://cdn.engagespot.co/serviceWorkerv2.js');

Enable Web Push in Engagespot App

By default, web push is disabled in your Engagespot app. After you’ve completed the above step, you should login to your Engagespot account, and enable web push under channels menu.

Add Engagespot Component to Your React App

You’ve setup service workers and enabled web push in your Engagespot App. Now, let’s give your user’s the option to enable notifications in your React App. For that, we need to install Engagespot react component.

Add the package to your React App via npm or yarn

npm i @engagespot/react-component

Now, import the component inside the source code, where you want the notification component to appear.

import Engagespot from "@engagespot/react-component";  

Render the Notification component inside any existing React component. For example, a bell icon place holder, or a Navigation component etc.

<Engagespot  
apiKey = "ENGAGESPOT_API_KEY"
userId = "youruser@example.com"
/>

Replace youruser@example.com with the variable where you store the unique user id of your app user. This can be their email id, or a UUID or any other unique identifier.

That’s it.

The next time when you reload your app, you can see a bell icon on your app. And clicking on the bell icon will show you a prompt to enable web push notifications.