Skip to main content

JS Client SDK (Front-End)

This client-side SDK for JavaScript allows you to show in-app notifications in your front-end.

Setup#

/* 1. Install using npm or yarn:
npm install notificationapi-js-client-sdk
yarn add notificationapi-js-client-sdk
*/
// 2. import or require:
import NotificationAPI from 'notificationapi-js-client-sdk';
const NotificationAPI = require('notificationapi-js-client-sdk').default;

Initialization#

The example below creates a NotificationAPI client that connects to our servers through a WebSocket connection from your front-end. It does not show anything yet.

Example
const notificationapi = new NotificationAPI({
clientId: YOUR_CLIENT_ID,
userId: UNIQUE_USER_ID
});
info

Initializing the library more than once is safe, but will generate unnecessary resources and network calls.

React users should follow the React section.

Parameters:

clientId (required)
Type: string

Your NotificationAPI account clientId. You can get it from here.

userId (required)
Type: string

The unique ID of the user in your system.

userIdHash Type: string

Only used for Secure Mode.

getUserPreferences()#

Allows you to access the raw data of the user's notification preferences from the front-end.

Please note that unless you require extreme customization, you can rely on showUserPreferences() function to display and edit notification preferences without any additional code.

Example
notificationapi.getUserPreferences().then((prefs) => {
console.log(prefs);
});
/* prints:
[
{
"notificationId": "new_order",
"title": "New Order",
"settings": [
{
"channel": "SMS",
"state": false,
"channelName": "SMS"
},
{
"channel": "EMAIL",
"state": true,
"channelName": "Email"
}
],
"subNotificationPreferences": []
},
... more items for all notifications
] */

Returns

getUserPreferences() : Promise<Preference[]>
interface Preference {
notificationId: string;
title: string; // the friendly title of the notification
settings: {
channel: string; // EMAIL, INAPP_WEB, SMS, CALL
channelName: string; // channel friendly name: Email, In-App, SMS, Call
state: boolean; // indicating the preference
}[];
subNotificationPreferences: Preference[]; // when using subNotificationIds, it will contain a similar item for each subNotificationId
}

patchUserPreference()#

Allows you to programmatically change the user's notification preferences from the front-end.

Please note that unless you require extreme customization, you can rely on showUserPreferences() function to display and edit notification preferences without any additional code.

Example
notificationapi.patchUserPreference('myNotificationId', 'EMAIL', false);

Parameters

notificationId (required)
Type: string

The ID of the notification in NotificationAPI.

channel (required)
Type: string

The channel for which you wish to change the setting.
Accepted values: EMAIL, INAPP_WEB, SMS, CALL.

state (required)
Type: boolean

The preference of the user. If set to false, the user will no longer receive the specified notification on the specified channel, until the state is set to true again through the API or the preferences popup.

subNotificationId (optional)
Type: string

For setting the preference of a subNotificationId within a notification.

showInApp()#

This function adds the in-app notifications (the bell icon along with all its functionality) to your app.

Sample

Example
notificationapi.showInApp({
root: 'parentDivID'
});

Parameters

root (required)
Type: string

The ID of the HTML element that will contain the NotificationAPI widget. Ideally an empty div.

popupPosition
Type: string (JS), PopupPosition enum (TS)

The position of the notifications popup relative to the button. Defaults to rightBottom.
Valid string options: topLeft, topRight, bottomLeft, bottomRight, leftTop, leftBottom, rightTop, rightBottom.

showUserPreferences()#

User preferences is accessible from the in-app popup (similar to the gif below). However, you may use this function to programmatically open the user preferences from your code.

Example
notificationapi.showUserPreferences();

Parameters

parent
Type: string
Default: undefined

When undefined (default behavior), the user preferences will show as a modal. Given this parameter, the user preferences will render in inline mode inside an existing HTML element on your page. You can pass the ID of the parent element to this parameter. Ideally, use an empty div for the parent.

With React.js#

React's state management and re-rendering causes this widget to be destroyed and re-initialized with every state change. To avoid this issue, place the initialization and the root element in a "memo"-ized React component. Example:

import NotificationAPI from 'notificationapi-js-client-sdk';
import { PopupPosition } from 'notificationapi-js-client-sdk/lib/interfaces';
import React, { memo, useEffect, useRef } from 'react';
const NotificationAPIComponent = memo((props) => {
const containerRef = useRef();
useEffect(() => {
const notificationapi = new NotificationAPI({
clientId: YOUR_CLIENT_ID,
userId: props.userId
});
notificationapi.showInApp({
root: 'container',
popupPosition: PopupPosition.BottomLeft
});
// Store a reference to the container DOM element.
const container = containerRef.current;
// This effect can run multiple times due to the `userId` changing
// or Hot Module Replacement (HMR). Ensure the container is cleared
// as `showInApp` will append to the container instead of overwriting it.
return () => {
container.innerHTML = '';
};
}, [props.userId]);
return <div id="container" ref={containerRef}></div>;
});
export default NotificationAPIComponent;

Secure Mode#

Front-end code is observable and mutable by end-users. Malicious actors can take advantage of this. For example, someone can impersonate another user on your website's chat tool or NotificationAPI by passing different parameters to the library. Secure Mode makes our front-end SDK safe against this threat.

Step by Step Guide

  1. Back-end: hash the userId using your client secret. Pass the hashed userId to your front-end. For example, from an API right after the page loads.
const hashedUserId = require('crypto') // crypto is part of nodejs
.createHmac('sha256', 'YOUR_CLIENT_SECRET')
.update('ACTUAL_USER_ID')
.digest('base64');
2. Front-end: pass the hashed userId to the NotificationAPI SDK:
new NotificationAPI({
root: '...',
clientId: '...',
userId: 'ACTUAL_USER_ID',
userIdHash: 'HASHED_USER_ID'
});
  1. Enable secure mode in your account settings. When our SDK starts, it sends both the userId and hashed userId to our servers and we compare the values to ensure the userId and its hash match, indicating userId has not been tampered.