Initial configuration

Before building your chat app, you must initialize and configure the Chat SDK.

Start by signing into the Admin Portal or creating an account if you don't have one yet.

Then, create an app on the Admin Portal. You will need a PubNub app to get a keyset that consists of a Subscribe Key and a Publish Key. These keys will let you establish a connection between PubNub and the chat app you're going to create with the Chat SDK.

When you create a new app on the Admin Portal, the first set of demo keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Keyset configuration

Each keyset has its own configuration settings in the Admin Portal. To develop some features in your chat app, you must enable appropriate settings on your app's keyset on the Admin Portal.

For example, to create or update users in your chat, you'll need to enable App Context on the keyset for PubNub to manage that user metadata. Similarly, you'll need to enable Presence to track a user's channel presence or enable Message Persistence to store messages in PubNub history. You can enable these features at any time - the docs will instruct you and show which setting needs enabling on your keyset for a given chat feature to work.

Initialize PubNub

Once you have a PubNub account and an app created on the Admin Portal, you can start initializing PubNub Client API context and establish account-level credentials.

To initialize PubNub with the Chat SDK, use the init() method.

You must provide at least these three parameters: publishKey, subscribeKey, or userId. Apart from the required parameters, you can also configure additional options when initializing the Chat SDK. These options will let you add configuration required to implement advanced chat features, like typing indicator, user offline/online presence, push notifications, or client-side limiting that prevents spamming.

The init() method takes the following parameters:

const chat = Chat.init({
publishKey: string,
subscribeKey: string,
userId: string,
typingTimeout?: number,
storeUserActivityInterval?: number,
storeUserActivityTimestamps?: boolean,
pushNotifications?: {
sendPushes?: boolean,
deviceToken?: string,
deviceGateway?: "apns2" | "gcm",
pnsTopic?: string,
apnsEnvironment?: "development" | "production"
rateLimitFactor?: number,
show all 23 lines

Input parameters

publishKeystringYesn/aSend messagesSpecifies the key used to publish messages on a channel.
subscribeKeystringYesn/aReceive messagesSpecifies the key used to subscribe to a channel.
userIdstringYesn/an/aUnique User ID that becomes your app's current user. It's a string of up to 64 characters that identifies a single client (end user, device, or server) that connects to PubNub. Based on User ID, PubNub calculates pricing for your apps' usage. User ID should be persisted and remain unchanged. If you don't set userId, you won't be able to connect to PubNub.
typingTimeoutnumberNo5000Typing IndicatorSpecifies the default timeout after which the typing indicator automatically stops when no typing signals are received. The default and maximum value is set to 5000 milliseconds (5 seconds).
storeUserActivityTimestampsbooleanNofalseUser's last online activity, global presenceSpecifies if you want to track the user's global presence in your chat app. The user's activity is tracked through the lastActiveTimestamp parameter on the User object.
storeUserActivityIntervalnumberNo600000User's last online activity, global presenceSpecifies how often the user global presence in the app should be updated. Requires storeUserActivityTimestamps to be set to true. The default value is set to 600000 milliseconds (10 minutes), and the minimum possible value is 60000 milliseconds (1 minute). If you try to set it to a lower value, you'll get the storeUserActivityInterval must be at least 60000ms error.
pushNotificationsobjectNon/aPush NotificationsList of parameters you must set if you want to enable sending/receiving mobile push notifications for iOS and Android devices, either through Apple Push Notification service (APNS) in version 2 or Firebase Cloud Messaging (FCM), formerly known as Google Cloud Messaging (GCM).
 → sendPushesbooleanNofalseas aboveThe main option for enabling sending notifications. It must be set to true if you want a particular client (whether a mobile device, web browser, or server) to send push notifications to mobile devices.

These push notifications are messages with a provider-specific payload (different for APNs and FCM) that the Chat SDK automatically attaches to every message. Chat SDK includes a default payload setup for APNs and FCM gateways in every message sent to the registered channels.

This is the only required option to enable if you want to send push notifications to Android devices. For iOS devices, you also have to configure apnsTopic.
 → deviceTokenstringNon/aas aboveOption for receiving notifications on iOS and Android devices.

A device token refers to the unique identifier assigned to a specific mobile device by a platform's push notification service. It targets and delivers push notifications to the intended app on that specific device. Suppose you don't set this option and try to run channel registration-related methods. In that case, you'll get the Device Token has to be defined in Chat pushNotifications config error.

Refer to the official Apple and Google docs to learn how to obtain a device token for the APNs and FCM services.
 → deviceGatewayapns2 or gcmNogcmas aboveOption for receiving push notifications on Android (gcm) or iOS (apns2) devices.
 → apnsTopicstringNon/aas aboveAn Apple specific-option for sending and receiving notifications.

This string is a bundle ID that you must define yourself for your iOS app so that Apple could enable push notifications for it in APNs. The string takes the following format: com.domainname.applicationname. Apple combines that ID with your Team ID (generated by Apple) and creates an App ID for your application.

To send pushes from an iOS device, you must also set sendPushes to true. To receive pushes on an iOS device, you must also set deviceGateway to apns2, define deviceToken, and apnsEnvironment. Suppose you don't configure apnsTopic, but set deviceGateway to apns2. In that case, you'll get the apnsTopic has to be defined when deviceGateway is set to apns2 error and Chat SDK won't attach the apns payload to messages.
 → apnsEnvironmentdevelopment or productionNodevelopmentas aboveOption for receiving notifications on iOS devices. When registering for push notifications, this option specifies whether to use the development or production APNs environment.
rateLimitFactornumberNo2Client-side rate limitingThe so-called "exponential backoff" which multiplicatively decreases the rate at which messages are published on channels.

It's bound to the rateLimitPerChannel parameter and is meant to prevent message spamming caused by excessive retries.

The default value of 2 means that if you set rateLimitPerChannel for direct channels to 1000 (one second) and try to send three messages on such a channel type within the span of one second, the second message will be published one second after the first one (just like the rateLimitPerChannel value states), but the third one will be published two seconds after the second one, meaning the publishing time is multiplied by 2.
rateLimitPerChannelobjectNon/aClient-side rate limitingClient-side limit (expressed in milliseconds) that states the rate at which messages can be published on a given channel type. Its purpose is to prevent message spamming in your chat app.

This parameter takes an object with these three parameters: direct, group, and public. For example, if you decide that messages on all direct channels must be published no more often than every second, set this parameter to 1000, like rateLimitPerChannel { direct: 1000 }.
 → directnumber (in milliseconds)No0 (no limit)as aboveRate set on all direct (1:1) channels at which messages can be published.
 → groupnumber (in milliseconds)No0 (no limit)as aboveRate set on all group channels at which messages can be published.
 → publicnumber (in milliseconds)No0 (no limit)as aboveRate set on all public channels at which messages can be published.
errorLoggerErrorLoggerImplementationNoErrorLoggerImplementation { setItem(key: string, params: ErrorLoggerSetParams): void, getStorageObject(): Record<string, unknown> }Error loggingSpecifies if any Chat SDK-related errors should be logged. It's enabled by default. The setItem method specifies where errors should be saved and the getStorageObject method returns an object with a list of errors. You can replace this implementation with your own.
cryptoModuleCryptoModule.aesCbcCryptoModuleNon/aMessage and file encryption/decryptionCryptography module used for encrypting and decrypting messages and files. It takes the cipherKey parameter as an argument. For more information and examples, refer to the Data security section.
 → cipherKeystringNon/aas aboveString used to automatically encrypt and decrypt all message and file data in your chat app.

Additional configuration options

Since the Chat SDK heavily relies on the latest JavaScript SDK for all the underlying methods, when initializing the Chat SDK client, you can also make use of all optional parameters that come with the JavaScript SDK.

For example, you may want to use Access Manager and initialize the Chat SDK with secretKey (in the server-side code) or authKey (in the client-side code). You can also decide how long the server will consider the client alive for presence (presenceTimeout) or how often the client will announce itself to the server (heartbeatInterval).

For the whole list of all such inherited optional parameters which you can define when initializing the Chat SDK instance, check the JavaScript SDK configuration document.

Output parameters

Promise<Chat>Object returning a new PubNub chat instance.

Basic usage

Required setup

Use this basic example to include the PubNub Chat SDK package in your code and initialize the client setting only the required parameters.

// include the PubNub Chat SDK package in your code before initializing the client. Underneath, that also installs the PubNub JavaScript SDK "pubnub" package as a dependency.
import { Chat } from "@pubnub/chat"

// initialize your Chat SDK client using your app keys from the Admin Portal and a unique user ID for your client that you'll come up with
const chat = Chat.init({
publishKey: "demo",
subscribeKey: "demo",
userId: "myUniqueUserId"

Typing indicator timeout

Initialize the PubNub Chat SDK and set the default typing indicator timeout value to 3000 milliseconds (three seconds).

import { Chat } from "@pubnub/chat"

const chat = Chat.init({
publishKey: "demo",
subscribeKey: "demo",
userId: "myUniqueUserId",
typingTimeout: "3000"

Client-side rate limiting

Initialize the PubNub Chat SDK and set the hard limit for message publishing on public channels to 3000 milliseconds (three seconds). If there are more publish retries within this limit, each next retry limit should be multiplied by 3.

import { Chat } from "@pubnub/chat"

const chat = Chat.init({
publishKey: "demo",
subscribeKey: "demo",
userId: "myUniqueUserId",
rateLimitPerChannel: {
public: 1000
rateLimitFactor: 3

Next steps

Now that you've initialized and configured the Chat SDK, you can start creating channels, adding users, and powering your app with all sorts of features.

Run our sample chat app that will guide you through the chat app creation process and help you get started.

How to work with various frameworks

Chat SDK is framework-agnostic, meaning you can use it with any framework that supports TypeScript, such as React, React Native, Vue, or Angular.

If you want to create a chat app with our Chat SDK or add a chat to an existing application built in one of these frameworks:

  1. Make sure you have these dependencies: yarn (>=1.22.19), Node.js (>=18.10.0), and code editor (for example, Visual Studio Code)

  2. Add framework and PubNub-specific imports to your project file and initialize the Chat SDK.

// React imports
import { useEffect, useState } from "react";
// PubNub imports
// Give access to selected Chat SDK entities
import { Chat } from "@pubnub/chat";

// Initialize Chat SDK
export function SomeChatComponent() {
const [chat, setChat] = useState<Chat>()

useEffect(() => {
// Define your PubNub API credentials and user ID here
const publishKey = "put-your-publish-key-here";
const subscribeKey = "put-your-subscribe-key-here";
const userId = "put-your-user-id-here";
show all 28 lines

If you want further guidance on how to create channels, add users, send messages, and create more advanced features in your chat app, check our sample app built in React:

Last updated on