Initial configuration
Initialize and configure the Chat SDK before building your chat app.
Prerequisites
- Sign in or create an account on the Admin Portal.
- Create an app to get your Publish Key and Subscribe Key.
A new app receives demo keys automatically. You can create multiple keysets per app. Use separate keysets for production and test environments.
Required keyset settings
Enable these features on your keyset in the Admin Portal:
- App Context - Store user and channel data
- Presence - Track online/offline status
- Message Persistence - Store message history
Download the SDK
The JavaScript Chat SDK is available as the @pubnub/chat package. You can install it using a package manager or load it directly from the PubNub CDN.
Package manager
Install the @pubnub/chat package using npm, yarn, pnpm, or bun:
npm install @pubnub/chat
yarn add @pubnub/chat
pnpm add @pubnub/chat
bun add @pubnub/chat
CDN
Alternatively, include the SDK directly in your HTML by referencing the PubNub CDN:
<script src="https://cdn.pubnub.com/sdk/js-chat/pubnub-chat.1.0.5.js"></script>
The JavaScript Chat SDK is also available on GitHub.
Initialize PubNub
Use the init() method to create a Chat SDK instance. Three parameters are required: publishKey, subscribeKey, and userId.
Optional parameters configure features like typing indicators, presence tracking, push notifications, and rate limiting.
Extended configuration
The Chat SDK supports all JavaScript SDK configuration options. For example, use authKey with Access Manager for production apps. See Additional configuration options for details.
Method signature
1const chat = Chat.init({
2 publishKey: string,
3 subscribeKey: string,
4 userId: string,
5 authKey?: string,
6 typingTimeout?: number,
7 storeUserActivityInterval?: number,
8 storeUserActivityTimestamps?: boolean,
9 pushNotifications?: {
10 sendPushes?: boolean,
11 deviceToken?: string,
12 deviceGateway?: "apns2" | "gcm",
13 apnsTopic?: string,
14 apnsEnvironment?: "development" | "production"
15 },
show all 33 linesInput parameters
publishKeyrequired#- Specifies the key used to publish messages on a channel.
- Feature
- Send messages
subscribeKeyrequired#- Specifies the key used to subscribe to a channel.
- Feature
- Receive messages
userIdrequired#- Unique User ID that becomes your app's current user. It's a string of up to 92 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.- Feature
- n/a
authKey#- If Access Manager is utilized, the client will use this
authKeyto authenticate restricted requests.- Feature
- n/a
typingTimeout#- Specifies the default timeout after which the typing indicator automatically stops when no typing signals are received. The default and maximum value is set to
5000milliseconds (5 seconds).- Feature
- Typing Indicator
storeUserActivityTimestamps#- Specifies if you want to track the user's global presence in your chat app. The user's activity is tracked through the
lastActiveTimestampparameter on theUserobject. storeUserActivityInterval#- Specifies how often the user global presence in the app should be updated. Requires
storeUserActivityTimestampsto be set totrue. The default value is set to600000milliseconds (10 minutes), and the minimum possible value is60000milliseconds (1 minute). If you try to set it to a lower value, you'll get thestoreUserActivityInterval must be at least 60000mserror. pushNotifications#- List 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).
- Feature
- Push Notifications
- property of pushNotifications:
sendPushes# - The main option for enabling sending notifications. It must be set to
trueif 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 configureapnsTopic.- Feature
- as above
- property of pushNotifications:
deviceToken# - Option 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 theDevice Token has to be defined in Chat pushNotifications configerror.
Refer to the official Apple and Google docs to learn how to obtain a device token for the APNs and FCM services.- Feature
- as above
- property of pushNotifications:
deviceGateway# - Option for receiving push notifications on Android (
gcm) or iOS (apns2) devices.- Feature
- as above
- property of pushNotifications:
apnsTopic# - An 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 setsendPushestotrue. To receive pushes on an iOS device, you must also setdeviceGatewaytoapns2, definedeviceToken, andapnsEnvironment. Suppose you don't configureapnsTopic, but setdeviceGatewaytoapns2. In that case, you'll get theapnsTopic has to be defined when deviceGateway is set to apns2error and Chat SDK won't attach theapnspayload to messages.- Feature
- as above
- property of pushNotifications:
apnsEnvironment# - Option for receiving notifications on iOS devices. When registering for push notifications, this option specifies whether to use the development or production APNs environment.
- Feature
- as above
rateLimitFactor#- The so-called "exponential backoff" which multiplicatively decreases the rate at which messages are published on channels.
It's bound to therateLimitPerChannelparameter and is meant to prevent message spamming caused by excessive retries.
The default value of2means that if you setrateLimitPerChannelfor direct channels to1000(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 therateLimitPerChannelvalue states), but the third one will be published two seconds after the second one, meaning the publishing time is multiplied by2.- Feature
- Client-side rate limiting
rateLimitPerChannel#- Client-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, andpublic. For example, if you decide that messages on alldirectchannels must be published no more often than every second, set this parameter to1000, likerateLimitPerChannel { direct: 1000 }.- Feature
- Client-side rate limiting
- property of rateLimitPerChannel:
direct# - Rate set on all direct (1:1) channels at which messages can be published.
- Feature
- as above
- property of rateLimitPerChannel:
group# - Rate set on all group channels at which messages can be published.
- Feature
- as above
- property of rateLimitPerChannel:
public# - Rate set on all public channels at which messages can be published.
- Feature
- as above
errorLogger#- Specifies if any Chat SDK-related errors should be logged. It's enabled by default. The
setItemmethod specifies where errors should be saved and thegetStorageObjectmethod returns an object with a list of errors. You can replace this implementation with your own.- Feature
- Error logging
customPayloads#- Property that lets you define your custom message payload to be sent and/or received by Chat SDK on one or all channels, whenever it differs from the default
message.textChat SDK payload.
It also lets you configure your own message actions whenever a message is edited or deleted.
For examples, check Custom payload.- Feature
- Send and receive messages
- property of customPayloads:
getMessagePublishBody# - Function that lets Chat SDK send your custom payload structure. It defines the structure of your own message payload's body (of
anytype) that you're sending through PubNub.
Expand the Message-related types section for more details on the requiredTextMessageContentstructure.
DefinegetMessageResponseBodywhenever you usegetMessagePublishBody.- Feature
- as above
- property of customPayloads:
getMessageResponseBody# - Function that lets Chat SDK receive your custom payload structure. Use it to let Chat SDK translate your custom message payload into the default Chat SDK message format (defined in
TextMessageContent).
Expand the Message-related types section for more details on the requiredTextMessageContentstructure.
DefinegetMessagePublishBodywhenever you usegetMessageResponseBody.- Feature
- as above
- property of customPayloads:
editMessageActionName# - A type of action you want to be added to your Message object whenever a published message is edited, like
"changed"or"modified".
The default message action used by Chat SDK is"edited".
Expand the Message-related types section for more details.- Feature
- as above
- property of customPayloads:
deleteMessageActionName# - A type of action you want to be added to your Message object whenever a published message is deleted, like
"removed".
The default message action used by Chat SDK is"deleted".
Expand the Message-related types section for more details.- Feature
- as above
- property of customPayloads:
reactionsActionName# - A type of action you want to be added to your Message object whenever a reaction is added to a published message, like
"reacted".
The default message action used by Chat SDK is"reactions".
Expand the Message-related types section for more details.- Feature
- as above
cryptoModule#- Cryptography module used for encrypting and decrypting messages and files. It takes the
cipherKeyparameter as an argument. For more information and examples, refer to the Data security section.- Feature
- Message and file encryption/decryption
- property of cryptoModule:
cipherKey# - String used to automatically encrypt and decrypt all message and file data in your chat app.
- Feature
- as above
syncMutedUsers#- Whether the mute list is synchronized across sessions and devices. For more information, refer to Sync muted users.
- Feature
- User moderation
emitReadReceiptEvents#- Controls which channel types automatically emit
receiptevents when messages are marked as read. When a channel type istrue, the Chat SDK sends areceiptsignal each time a user callssetLastReadMessage(),setLastReadMessageTimetoken(), ormarkAllMessagesAsRead(), enabling other channel members to receive updates viaonReadReceiptReceived().- Feature
- Read receipts
Sync muted users
The syncMutedUsers parameter determines whether the mute list is synchronized across sessions and devices using a specific App Context User object.
When set to false, the mute list modifications are stored only for the duration of the current session. Once the session ends, the mute list is cleared.
When set to true, the client-side mute list is automatically saved and retrieved from App Context, ensuring that the muted user list persists beyond the current session. App Context uses a designated channel where all mute list data is sent: PN_PRV.$currentUserId.mute1.
Mute list and Access Manager
If you use Access Manager within your chat app and syncMutedUsers is enabled, you must grant the Chat SDK user the following permissions:
readpermission to thePN_PRV.$currentUserId.mute1channel.update,delete, andgetpermissions for thePN_PRV.$currentUserId.mute1user.
Make sure to change $currentUserId to the user ID of the chat user that will use the mute list functionality.
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
| Type | Description |
|---|---|
Promise<Chat> | Object returning a new PubNub chat instance. |
Sample code
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.
1// 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.
2import { Chat } from "@pubnub/chat"
3
4// 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
5const chat = await Chat.init({
6 publishKey: "demo",
7 subscribeKey: "demo",
8 userId: "myUniqueUserId"
9})
Typing indicator timeout
Initialize the PubNub Chat SDK and set the default typing indicator timeout value to 3000 milliseconds (three seconds).
1import { Chat } from "@pubnub/chat"
2
3const chat = Chat.init({
4 publishKey: "demo",
5 subscribeKey: "demo",
6 userId: "myUniqueUserId",
7 typingTimeout: 3000
8})
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.
1import { Chat } from "@pubnub/chat"
2
3const chat = Chat.init({
4 publishKey: "demo",
5 subscribeKey: "demo",
6 userId: "myUniqueUserId",
7 rateLimitPerChannel: {
8 public: 1000
9 },
10 rateLimitFactor: 3
11})
Initialize Chat SDK with Access Manager
Use a PubNub SDK instance initialized with secretKey to generate a token and return it to the client-side code. Then, initialize the PubNub Chat SDK and set the authKey to the token returned from the server-side code.
1const tokenReturnedFromServer = chatInstanceWithSecretKey.sdk.grantToken({
2 ttl: 60, // This 'ttl' variable will still determine how long the token is valid (in minutes)
3 resources: {
4 uuids: {
5 "user_alice": {
6 get: true,
7 update: true
8 }
9 },
10 channels: {
11 "chat_room_123": {
12 read: true,
13 write: true,
14 get: true,
15 }
show all 20 lines1const chat = Chat.init({
2 publishKey: "demo",
3 subscribeKey: "demo",
4 userId: "myUniqueUserId",
5 authKey: "tokenReturnedFromServer" // This is the token passed from the server-side code
6})
Custom payload
When initializing Chat SDK, you can pass your custom message payload structure using the customPayloads object and related properties. This will let Chat SDK correctly interpret your app's messages when sending and receiving them.
Define custom payload for all channels
Let's say your app doesn't follow the default message.text message body structure imposed by Chat SDK but instead uses the my.custom.payload.structure.text structure.
To successfully communicate with PubNub and send/receive messages through Chat SDK, pass your custom payload to all channels. Additionally, define your custom action names to be added to messages when they're edited or deleted.
1import { Chat } from "@pubnub/chat"
2
3const chat = Chat.init({
4 publishKey: "demo",
5 subscribeKey: "demo",
6 userId: "myUniqueUserId",
7 // If you don't define custom payload, messages on all channels will have the default "message.text" format
8 customPayloads: {
9 // Pass your custom message body structure so the Chat SDK can interpret your messages when sending them
10 getMessagePublishBody: ({ type, text, files }) => {
11 return {
12 my: {
13 custom: {
14 payload: {
15 structure: text,
show all 41 linesDefine custom payload for one channel
Let's say your app doesn't follow the default message.text message body structure imposed by Chat SDK for support-channel but instead uses the my.custom.payload.structure.text structure to communicate with PubNub.
Pass your custom payload to support-channel to successfully communicate with PubNub and send/receive messages through Chat SDK. Additionally, define your custom action names to be added to messages when they're edited or deleted.
The code sets up a PubNub chat instance with specific handlers for processing message payloads differently based on the channel.
1import { Chat } from "@pubnub/chat"
2
3const chat = Chat.init({
4 publishKey: "demo",
5 subscribeKey: "demo",
6 userId: "myUniqueUserId",
7 // If you don't define custom payload, messages on all channels will have the default "message.text" format
8 customPayloads: {
9 // Pass your custom message body structure so the Chat SDK can interpret your messages when sending them on "support-channel"
10 getMessagePublishBody: ({ type, text, files }, channelId) => {
11 // Define which channel should use custom payload
12 if (channelId === "support-channel") {
13 return {
14 my: {
15 custom: {
show all 61 linesDestroy Chat instance
Use the destroy() method to release all resources held by the Chat instance and the underlying PubNub SDK instance. Call this when your app shuts down or when you no longer need the Chat SDK — for example, on user logout or component unmount.
Method signature
1chat.destroy()
Input
None.
Output
None. This is a fire-and-forget cleanup method.
Sample code
1import { Chat } from "@pubnub/chat"
2
3const chat = await Chat.init({
4 publishKey: "demo",
5 subscribeKey: "demo",
6 userId: "myUniqueUserId"
7})
8
9// Clean up resources when the app shuts down or the user logs out
10chat.destroy()
Next steps
After initialization, you can:
- Run the sample chat app to see a working example
- Create channels and users
- Add features like messaging, typing indicators, and presence
Framework integration
The Chat SDK works with any TypeScript-compatible framework: React, React Native, Vue, Angular, and others.
Requirements:
- yarn (>=1.22.19) or npm
- Node.js (>=18.10.0)
- Code editor (for example, Visual Studio Code)
- React
- React Native
- Vue
- Angular
1// React imports
2import { useEffect, useState } from "react";
3// PubNub imports
4// Give access to selected Chat SDK entities
5import { Chat } from "@pubnub/chat";
6
7// Initialize Chat SDK
8export function SomeChatComponent() {
9 const [chat, setChat] = useState<Chat>()
10
11 useEffect(() => {
12 // Define your PubNub API credentials and user ID here
13 const publishKey = "put-your-publish-key-here";
14 const subscribeKey = "put-your-subscribe-key-here";
15 const userId = "put-your-user-id-here";
show all 28 lines1// React imports
2import { useEffect, useState } from "react";
3// PubNub imports
4// Give access to selected Chat SDK entities
5import { Chat } from "@pubnub/chat";
6
7// Initialize Chat SDK
8export function SomeChatComponent() {
9 const [chat, setChat] = useState<Chat>()
10
11 useEffect(() => {
12 // Define your PubNub API credentials and user ID here
13 const publishKey = "put-your-publish-key-here";
14 const subscribeKey = "put-your-subscribe-key-here";
15 const userId = "put-your-user-id-here";
show all 28 lines1// Vue imports
2import { reactive } from "vue"
3// PubNub imports
4// Give access to selected Chat SDK entities
5import { Chat } from "@pubnub/chat"
6
7// Define your PubNub API credentials and user ID here
8const publishKey = "put-your-publish-key-here"
9const subscribeKey = "put-your-subscribe-key-here"
10const userId = "put-your-user-id-here"
11
12// Initialize Chat SDK
13interface State {
14 chat: Chat | null
15}
show all 30 lines1// Angular imports
2import { BrowserModule } from '@angular/platform-browser';
3import { NgModule } from '@angular/core';
4import { AppComponent } from './app.component';
5// PubNub imports
6// Give access to selected Chat SDK entities
7import { Chat } from "@pubnub/chat";
8
9@NgModule({
10 declarations: [
11 AppComponent
12 ],
13 imports: [
14 BrowserModule
15 ],
show all 39 linesFor a complete example with channels, users, and messaging, see the React Getting Started app and guide.