Announcing the New PubNub Chat SDK
Published: 2023-10-13 10:20:51

We are excited to announce the new [PubNub Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk/overview), the easiest way for developers to create new chat applications or add in-app chat to existing applications.

We frequently see customers implementing the same chat features over and over again with our traditional SDKs; for example, most chat apps will handle group messaging, show a typing indicator, and have a way of organizing users.  Rather than expect everyone to implement these high-level features using our traditional APIs, we thought: “Why not expose a dedicated API specifically for chat features?”  The Chat SDK was created to address that need.  Best of all, since the Chat SDK is still built on the PubNub platform, you get all the great PubNub features we offer, such as compliance, scalability, and security (through the Access Manager).

Any developer targeting TypeScript can use the Chat SDK in their project.  We are framework-agnostic, so the Chat SDK is a great choice regardless of whether you are working with Angular, React, Vue, Ionic, or any other framework that supports TypeScript, both on web and mobile platforms.  Additionally, the Chat SDK is **UI agnostic**, so it gives you the freedom to create unique chat experiences with either your own UI or any pre-built Chat UI available on the market. Why TypeScript?  This was in response to customer feedback and where we saw the most demand for what is our first use-case-specific API.

## Features of the PubNub Chat SDK

To add [chat functionality](https://www.pubnub.com/solutions/chat/) to your application, the PubNub Chat SDK has been built to support the following features out of the box:

- **Conversation (Channel) Management:** Create direct 1:1 conversations or larger group chats, inviting others to join or leave as needed.

- **Manage Users:** Detect users’ online status, mention them in conversations, and moderate their content.

- **Basic Messaging:** Send and receive messages, emojis, links, and files to any number of recipients.   

- **Advanced Messaging:** Forward, Quote, or Pin messages.  The SDK also supports read receipts, unread message counts, and a typing indicator to see if other channel participants are typing.

- **Mobile app support:** Easy integration with Android (FCM) and iOS (APNS) push messaging, giving you a consistent approach to offline messages without worrying about platform-specific implementation. 

The Chat SDK natively supports concepts such as ‘Users,’ ‘Messages,’ and ‘Channels,’ which are used as follows:

## Users

Create a [User](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/create) to represent anybody who will participate in a chat conversation.  Users have all the properties you would expect of a chat system, like nickname & avatar, and you can assign custom properties as needed, such as an external ID to match the user with your external system.

```js
// reference the "chat" object and invoke the "createUser()" method
const user = await chat.createUser(
  "support_agent_15",
  {
    name: "John Smith",
    profileUrl: "https://randomuser.me/api/portraits/men/1.jpg",
    custom: {
      title: "VP Marketing",
      linkedInUrl: "https://www.linkedin.com/mkelly_vp"
    }
  }
)
```
Once created, APIs exist to [retrieve](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/details), [update](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/updates#update-user-details), [delete](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/delete), or [listen for any changes](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/updates#get-user-updates) to a user’s properties. 

## Channels

Having created representations for the system’s users, they need to be added to conversations.  The Chat SDK uses the concept of [channels](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create) to represent a conversation between users, and a conversation can either be [direct](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create#create-direct-channel), between just two individuals, a [group conversation](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create#create-group-channel) amongst multiple users, or a [public group](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create#create-public-channel) without any limits on membership.

Assuming two users have already been created, you can create a group conversation as follows.  Note that optional metadata can be added to the channel, such as name and purpose.

```js
// reference both agents you want to talk to
const user1 = await chat.getUser("agent-007")
const user2 = await chat.getUser("agent-008")

// add the channel ID, name, and topic
const { channel, hostMembership, inviteeMembership } = await chat.createGroupConversation(
  {
    users: 
    [
      user1,
      user2
    ],
    channelId: "group-chat-1"
    channelData: {
      name: "Weekly syncs on customer XYZ"
    },
    membershipData: {
      custom: {
        purpose: "premium-support"
      }
    }
  }
)
```

The users passed in at channel creation only represents the initial state, you can [join](https://pubnub.com/docs/chat/chat-sdk/build/features/channels/join) or [leave](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/leave) an existing conversation at any time or other users can [invite](https://pubnub.com/docs/chat/chat-sdk/build/features/channels/invite#invite-one-user) you to an existing channel.  Other APIs also exist to manage both the [channel](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/updates) and [channel membership](https://pubnub.com/docs/chat/chat-sdk/build/features/channels/membership).


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y0qkfgnkv4y4fpyvitab.png)

## Messages

With the user now a member of one or more channels, messages can be sent and received over that channel. 

_Note: You don’t strictly need to be a member of a channel to send and receive messages, but membership is required for more advanced features such as presence and mentions, so it is recommended.  See our [documentation](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/send-receive#receive) for more details._

To receive messages, first [connect](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/watch) to the channel and specify a callback to be invoked when new messages arrive.

```js
// reference the "channel" object
const channel = await chat.getChannel("support")
// invoke the "connect()" method
channel.connect((message: Message) => {
  console.log(
    "Message received on channel: " + message.content.text
  )
})
```

Sending messages is very flexible, but in its simplest form, the sendText method is used to send a basic text message:

```js
// reference the channel where you want to send a text message
const channel = await chat.getChannel("support")
// invoke the "sendText()" method on the "channel" object
const message = await channel.sendText(
  "Hi, Everyone!",
  {
    storeInHistory: true,
    meta: {
      messageImportance: "high"
    },
  }
)
```

Note that the message is (optionally) persisted with `storeInHistory` and additional metadata can be associated with the message.

You are not limited to sending textual messages, you can send [files](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/files) and [links](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/links), or react with [emojis](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/reactions).  Messages can be [forwarded](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/forward), [quoted](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/quotes), [pinned](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/pinned), and you can even spawn [threads](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/threads) or receive [read receipts](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/read-receipts) in reply.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsncooqbdi530ekt59oe.png)

## Combining Users, Channels, & Messages

Having configured your Users and Channels, as well as each user’s channel memberships, you can take advantage of powerful capabilities offered by the Chat SDK:

**User Presence and Online Status:** Increase interactivity by tracking which users are active or away with the ‘[online status](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/presence)’ capability. See who is available on each channel or globally using the ‘channel [presence](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/presence#global-presence)’ feature.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1updbhpv4k52u1xmmeu3.png)

**@Mention Users in Messages:** When composing messages, users can see a [list of suggested users](https://pubnub.com/docs/chat/chat-sdk/build/features/users/mentions) when they start typing ‘@,’ sourced either globally or from only members of that channel.  Since the SDK stores the list of mentioned users as a separate data structure alongside the message, you can use it to send notifications according to your business logic.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yayg6g6bufghhggzukjy.png)

**History:** All messages and files can be optionally stored in persistent storage and assigned a custom time to live (ttl).  Message storage is [certified compliant](https://www.pubnub.com/blog/were-soc-2-type-ii-compliant/), meaning you can build applications that require GDPR, HIPAA, or SOC2 with the Chat SDK.  This list is incomplete, so please [contact our expert team](https://www.pubnub.com/company/contact-sales/) if you have specific requirements. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h6ikd1a1gytptwwaa244.png)

**Edit and Delete Messages:** After messages are sent, they can be optionally [edited](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/updates) or [deleted](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/delete) as needed.  As the developer, you have complete control - you can choose to retain deleted messages in your history or delete them entirely.  


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/peglv584f7qfviwdof5x.png)

**Moderation:** The Chat SDK allows you to [report or flag](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/moderation) offensive messages.

**Typing Indicator:** Dedicated APIs for start and stop typing allow you to track [who is typing](https://pubnub.com/docs/chat/chat-sdk/build/features/typing-indicator) on any individual channel.  The Chat SDK will handle all the timeout logic for you, so you don’t have to worry about keeping track of arrays of actively typing users.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9n02oh4azoyf6kk5gr8p.png)

**Mobile Push Notifications:** PubNub has built-in support for [mobile push notifications](https://pubnub.com/docs/chat/chat-sdk/build/features/push-notifications), so regardless of whether your users are running Android or iOS, you can notify users with the same platform-agnostic Chat API you use to send messages.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wrzgwi1of2g4gld27mrd.png)

## Implementation Details

These are the high-level building blocks of the chat SDK.  Please check out our [docs](https://pubnub.com/docs/chat/chat-sdk/build/configuration) or the [full demo](https://github.com/pubnub/js-chat/tree/master/samples/react-native-group-chat) to learn more about the implementation details.  Additional resources can also be found at the end of this article.

## Selecting an SDK: The Chat SDK or Another PubNub SDK?

Until the release of the [PubNub Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk/learn/why-chat-sdk), developers would use one of our traditional SDKs, for example, the [JavaScript SDK](https://www.pubnub.com/docs/sdks/javascript), and build chat functionality based on the general JavaScript API.  This is certainly possible to do, and thousands of developers have already done so, but the process was more complicated than it needed to be for developers specifically developing chat apps.

Let’s take, for example, how to implement an unread message counter in both the JavaScript SDK and the Chat SDK:


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x0jh34kmkrn3gzyezmgy.png)

### An unread message counter using the JavaScript SDK:

1. For the current user, viewing some specific channel, set the timetoken to indicate the latest message the user viewed.  

    The recommended way to do this is to use PubNub AppContext to store metadata associated with the user’s membership of the channel, setting `lastReadTimetoken` as required.

2. To determine the number of unread messages on any specific channel, call the [messageCounts API](https://www.pubnub.com/docs/sdks/javascript/api-reference/storage-and-playback#message-counts) and pass in both: 

    The channel name and the last viewed timetoken, as stored in PubNub AppContext and set in the previous step.

This is how our [showcase app](https://github.com/PubNubDevelopers/PubNub-Showcase/tree/main) implements the unread message count when the app first loads; specifically, please see [message.js](https://github.com/PubNubDevelopers/PubNub-Showcase/blob/main/web/chat/message.js) and [chat.js](https://github.com/PubNubDevelopers/PubNub-Showcase/blob/main/web/chat/chat.js).

### An unread message counter using the Chat SDK:

As detailed in the Chat SDK documentation for [unread messages](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/unread):

1. For the current user’s channel membership, specify the last read message using the `setLastReadMessage()` API, which takes a Message as an argument.

    The concepts of ‘channel membership’ and ‘messages’ are inherent parts of the Chat SDK.

2. Call the `getUnreadMessagesCount()` API on the current user’s channel membership.

Also, the Chat SDK [unread messages](https://pubnub.com/docs/chat/chat-sdk/build/features/messages/unread) documentation features an ‘Under the hood’ section, which explains how the Chat SDK is implemented… You will see that ‘under the hood’ the two implementations are identical.  **This means neither approach is better from a technical standpoint, but the Chat SDK is easier to understand and more user-friendly**. 

## Getting Started with the PubNub Chat SDK

The PubNub Chat SDK is available from yarn and can be installed as follows:

```shell
yarn add @pubnub/chat
```

Please see our [Getting Started walkthrough](https://pubnub.com/docs/chat/chat-sdk/build/sample-chat) or [video tutorial](https://youtu.be/_iHHCUn4aMU) to start integrating the PubNub Chat SDK with your application.

## Resources and Next Steps

The following resources are available for our Chat SDK:

### Documentation:

Our documentation page contains a [full API reference](https://www.pubnub.com/docs/chat/chat-sdk/build/configuration), a [getting started walkthrough](https://pubnub.com/docs/chat/chat-sdk/build/sample-chat), and a primer to explain some of the [concepts and terminology](https://www.pubnub.com/docs/chat/chat-sdk/learn/glossary) used by the SDK.

### Demos:

We have several pre-built demos, which can all be found in the [js-chat](https://github.com/pubnub/js-chat/tree/master) monorepo on GitHub.  

The [React Native Group Chat Demo](https://github.com/pubnub/js-chat/tree/master/samples/react-native-group-chat) is a fully featured showcase for the Chat SDK and should be your first stop to understand the capabilities of the API.  

For a simple introduction to the Chat SDK, please see the [Getting Started demo](https://github.com/pubnub/js-chat/tree/master/samples/getting-started), which is referenced by the [documentation](https://pubnub.com/docs/chat/chat-sdk/build/sample-chat) & [video tutorial](https://youtu.be/_iHHCUn4aMU) and uses React. 

See the readme file associated with each demo for instructions on how to get started.  


## Feedback Welcome

We encourage you to download and try out the new SDK for your real-time applications and provide us with valuable feedback.  You can contact [PubNub support](https://support.pubnub.com/hc/en-us) or the developer relations team directly at [devrel@pubnub.com](devrel@pubnub.com).  Be on the lookout for additional Chat SDK resources in the future, and happy coding!