How to Manage User Channel Membership with the PubNub Chat SDK
Tags: chatsdk, typescriptsdk, chatjavascript
Published: 2023-12-20 07:43:05

Introduction to the PubNub Chat SDK
-----------------------------------

The PubNub Chat SDK, available for TypeScript and JavaScript applications, exposes a set of APIs designed to make it easy to add powerful and flexible chat features to your app with minimum development. Chat options like [quoting](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/quotes), [mentioning users](https://www.pubnub.com/docs/chat/chat-sdk/build/features/users/mentions), [channel references](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/references), [threads](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/threads), [read receipts](https://www.pubnub.com/docs/chat/chat-sdk/build/features/messages/read-receipts), and [typing indicators](https://www.pubnub.com/docs/chat/chat-sdk/build/features/typing-indicator) are supported natively by the SDK, letting you build a full-fledged app quickly.

Please refer to our [documentation](https://www.pubnub.com/docs/chat/chat-sdk/overview) and [sample chat app](https://www.pubnub.com/docs/chat/chat-sdk/build/sample-chat) to get started with the Chat SDK. Our [tutorial](https://www.pubnub.com/tutorials/chat-sdk/) will walk you through the basic functionality of the Chat SDK and touch on some more advanced features whilst our [hosted demo](https://www.pubnub.com/demos/chat-sdk-mobile/) will show the Chat SDK in action.

This how-to is part of a **series of posts** diving into some of the more powerful features of the PubNub Chat SDK. The series can be read in any order, but the list of related articles is below:

-   [How to Manage User Channel Membership with the Chat SDK](https://pubnub.com/how-to/chat-sdk-manage-user-channel-membership/)
-   [How to Add Reactions and Emojis to Messages with the Chat SDK](https://pubnub.com/how-to/chat-sdk-add-reactions-to-messages/)
-   [How to Create Threads and Quote Messages with the Chat SDK](https://pubnub.com/how-to/chat-sdk-create-threads-and-quote-messges/)
-   [How to Mention Users and Channels with the Chat SDK](https://pubnub.com/how-to/chat-sdk-mention-users/)

Managing User Channel Memberships
---------------------------------

The Chat SDK defines several types that are important to understand channel membership:

-   [Users](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/user) represent individuals taking part in a conversation.
-   [Channels](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/channel) represent a conversation between multiple users. The documentation uses the analogy that each channel represents a single ‘chat room.’ Channels can be direct (i.e., a 1:1 conversation between just two users, ‘group’ (i.e., between multiple named users), or ‘public.’
-   [Memberships](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/membership) represent a relationship between Users and Channels with optional accompanying metadata.

This guide will discuss how to create and manage those channel memberships.

### How users join a channel

There are multiple ways that a user can become a member of a channel. When [direct](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create#create-direct-channel) or [group](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create#create-group-channel) channels are created, the user(s) in that conversation are specified as arguments during creation.

In the example below, [taken from the documentation](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create#basic-usage-1), the two users ‘agent-007’ and ‘agent-008’ are made members of channel ‘group-chat-1’

```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"
    …
  }
)
```

You can query whether a user is a member of a channel in a number of ways, and you can find full details in the [documentation for channel membership](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/membership). For example, to get the members of the channel we just created:

```js
// reference the "channel" object
const channel = await chat.getChannel("group-chat-1")
const members = await channel.getMembers()
//  members contains both users, so members.total === 2
```

If users are not assigned to a channel during its creation, they can join or leave later using the corresponding [join()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/join) and [leave()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/leave) methods, allowing you to have dynamic channels. Users can also be [invited](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/invite) to become a member of a channel.

You can see this behavior in the short demo below. Since this is a live, working demo, notice that your channel membership will persist even after you refresh the page.

Interactive Demo
----------------

  
**If the embedded content is not available** on this page, it can also be viewed at [https://chat-sdk-how-to-membership.netlify.app/](https://chat-sdk-how-to-membership.netlify.app/)

The code that drives this demo is available on [GitHub](https://github.com/PubNubDevelopers/Chat-SDK-How-Tos/tree/main/membership), but the key points are:

Ensure you have an instance of the [Chat object](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/chat) instantiated in your app

```js
const chat = await Chat.init({
  publishKey: "YOUR_PUBLISH_KEY",
  subscribeKey: "YOUR_SUBSCRIBE_KEY",
  userId: "YOUR_USER_ID",
})
```

There are a lot of possible parameters you can pass to the Chat SDK, but for channel membership, you do not need anything more than the standard publish key, subscribe key, and user ID. If all of this is new to you, and you’re not sure where to get started, please check out the [initial configuration](https://www.pubnub.com/docs/chat/chat-sdk/build/configuration) section in our documentation.

Join a channel. This code also registers to receive membership updates, which is discussed in the next section.

```js
async function join(channelName: string)
  {
    if (chat)
    {
      const channel = await chat.getChannel(channelName)
      const channelMembership = await channel?.join(() => null)
      channelMembership?.membership.streamUpdates(async (membership) => {
        //  Stream updates on the channel as follows
        console.log(membership)
      })
      
      //  For brevity, ignore that this call could contain multiple pages of memberships
      const {memberships} = await chat.currentUser.getMemberships()
      setMyMemberships(memberships) 
    }
  }
```

As mentioned in the code comments above, the call to [user.getMemberships()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/membership#get-membership) may contain paginated data if there are too many channels.

The code which powers the ‘leave channel’ buttons in the demo is as follows:

```js
async function leave(channelName: string)
  {
    if (chat)
    {
      const channel = await chat.getChannel(channelName)
      await channel?.leave();
      //  For brevity, ignore that this call could contain multiple pages of memberships
      const {memberships} = await chat.currentUser.getMemberships()
      setMyMemberships(memberships) 
    }
  }
```

To keep the demo simple, there is only a single user, and only the user’s own membership is considered. In a real application, you will have multiple users, each with their own channel memberships. A more [realistic demo](https://www.pubnub.com/demos/chat-sdk-mobile/) is available for our Chat SDK and is discussed at the bottom of this guide.

### Channel membership metadata

The [Membership](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/membership) object allows you to specify custom metadata related to the association between the channel and user; for example, if this was a chat related to a support inquiry, you might store the user’s role as a {role: ‘support technician’}.

Metadata can be declared when the membership is created or can be [updated](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/membership#update) at any point by the individual user.

To keep track of when membership metadata is updated, the Chat SDK provides the [streamUpdates() and streamUpdatesOn()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/membership#get-updates) methods for the [Membership](https://www.pubnub.com/docs/chat/chat-sdk/learn/chat-entities/membership) object.

As shown in the earlier demo, you can track changes to the membership metadata as follows:

```js
channelMembership?.membership.streamUpdates(async (membership) => {
  //  Stream updates on the channel as follows
  console.log(membership)
})
```

### Why should users join a channel?

One assumption would be that users need to join a channel to receive messages on that channel, but this is not the case. To receive messages on a channel, you can invoke the [connect()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/watch) method, where you can provide a callback to be invoked whenever a message is received. If you were not made a member of a channel when it was [created](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/create), you would need to call [connect()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/watch) separately, but calling [join()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/join) will invoke connect() for you automatically.

If you are familiar with PubNub, this [connect()](https://www.pubnub.com/docs/chat/chat-sdk/build/features/channels/watch) call is analogous to [subscribe()](https://www.pubnub.com/docs/general/channels/subscribe) and [addListener()](https://www.pubnub.com/docs/general/messages/receive).

So, why should you join a channel? Joining a channel and the associated channel memberships are fundamental to how the Chat SDK understands user relationships, so it is required to use many more powerful SDK features, such as read receipts, mentioning users, unread message counts, moderation, and the typing indicator.

Membership Summary
------------------

-   **What is it?** A relationship between a User and a Channel, with customizable metadata.
-   **How is a membership created?** Users can be associated with a channel during its creation, or they can join themselves or be invited by others to a channel after it has been created.
-   **How is a membership destroyed?** Users can leave a channel at any time
-   **How is a membership tracked?** Members of a channel can be queried with getter functions, and you can be notified of changes by registering for updates.
-   **Common Pitfalls:** Membership does not always mean you will receive messages on a channel; take care to read the documentation when you need to call connect() separately.
-   **Any other restrictions?** Although you can join ‘public’ channels, several features, such as read receipts or the typing indicator, are not supported for this type of channel.
-   **What features are required on the PubNub Keyset?** Be sure to enable App Context on your keyset.

Demo: User Channel Membership in Action
---------------------------------------

Our Chat SDK Demo for Mobile, available as a [hosted demo](https://www.pubnub.com/demos/chat-sdk-mobile/) with full source code available on [GitHub](https://github.com/pubnub/js-chat/tree/master/samples/react-native-group-chat), uses Membership to manage User conversations. **You should also see the demo rendered in an iFrame at the bottom of this section**.

![Two smartphones displaying chat application interfaces, one with chat settings and the other showing a conversation window.](https://images.ctfassets.net/3prze68gbwl1/7yuFtoqdBT21RfmAhxKSDs/ce53179847eb502be3ef8c0f8ea1e686/membership.png)

Follow these steps to see memberships used in our demo:

1.  Log in to the application, choosing a random user id for each of the two devices.
2.  Create a group by clicking on the ‘new chat’ icon, then selecting ‘Create group chat’
3.  Choose the two user IDs you just logged in as, and assign a name for the group.
4.  Behind the scenes the application has created a membership to associate each of the two users with the newly created group.
5.  Enter the group conversation by clicking on the entity that was created under the ‘Groups’ section.
6.  Tap on the name of the group at the top of the screen to see your user’s chat settings (as shown in the left hand image, above)
7.  Notice how this user’s name is a ‘Member’ of the chat.
8.  Notice that if you back out of the conversation or even log out of and back into the app, the reactions are retained and read from the message history.

  
**If the embedded content is not available** on this page, it can also be viewed at [https://pubnubdevelopers.github.io/Chat-SDK-Demo/mobile/](https://pubnubdevelopers.github.io/Chat-SDK-Demo/mobile/)

How can PubNub help you?
========================

This article was originally published on [PubNub.com](https://pubnub.com/how-to/chat-sdk-manage-user-channel-membership/)

Our platform helps developers build, deliver, and manage real-time interactivity for web apps, mobile apps, and IoT devices.

The foundation of our platform is the industry's largest and most scalable real-time edge messaging network. With over 15 points-of-presence worldwide supporting 800 million monthly active users, and 99.999% reliability, you'll never have to worry about outages, concurrency limits, or any latency issues caused by traffic spikes.

Experience PubNub
-----------------

Check out [Live Tour](https://www.pubnub.com/tour/introduction/) to understand the essential concepts behind every PubNub-powered app in less than 5 minutes

Get Setup
---------

Sign up for a [PubNub account](https://admin.pubnub.com/signup/) for immediate access to PubNub keys for free

Get Started
-----------

The [PubNub docs](https://www.pubnub.com/docs) will get you up and running, regardless of your use case or [SDK](https://www.pubnub.com/docs)