Manage the user-channel membership relationship

Requires App Context

Enable App Context for your keyset in the Admin Portal.

A Membership entity is created when a user joins or is invited to a channel, and ends when the user leaves.

Interactive demo​

Sample React app demonstrating user-channel membership.

Want to implement something similar?

Test it out​

Choose whether you want to join or leave a given channel and wait until you get notified when that happens.

Get members​

Get all members of a channel with getMembers().

icon

Under the hood

Method signature​

This method takes the following parameters:

1channel.getMembers({
2 filter?: string,
3 sort?: object,
4 limit?: number,
5 page?: {
6 next?: string,
7 prev?: string,
8 }
9}): Promise<{
10 page: {
11 next: string;
12 prev: string;
13 };
14 total: number;
15 status: number;
show all 17 lines

Input​

* required
ParameterDescription
filter
Type: string
Default:
n/a
Expression used to filter the results. Returns only these members whose properties satisfy the given expression. The filtering language is defined here.
sort
Type: object
Default:
n/a
Key-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated. Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"}. By default, the items are sorted by the last updated date.
limit
Type: number
Default:
100
Number of objects to return in response. The default (and maximum) value is 100.
page
Type: object
Default:
n/a
Object used for pagination to define which previous or next result page you want to fetch.
> next
Type: string
Default:
n/a
Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
> prev
Type: string
Default:
n/a
Random string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. Ignored if the next parameter is supplied.

Output​

ParameterDescription
Promise<>
Type: object
Returned object containing these fields: page, total, status, and members.
> page
Type: object
Object used for pagination to define which previous or next result page you want to fetch.
>> next
Type: string
Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
>> prev
Type: string
Random string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. Ignored if the next parameter is supplied.
> total
Type: number
Total number of channel members.
> status
Type: number
Status code of a server response, like 200.
> members
Type: Membership[]
List of all related memberships.

Sample code​

List all members of the support channel on the premium support plan.

1// reference the "channel" object
2const channel = await chat.getChannel("support")
3
4// get the list of all members with the premium support plan
5await channel.getMembers({
6 filter: "custom.support_plan == 'premium'"
7})

Get membership​

Get all channel memberships for a user with getMemberships().

icon

Under the hood


To list all channels, use getChannels() instead.

Method signature​

This method takes the following parameters:

1user.getMemberships({
2 filter?: string,
3 sort?: object,
4 limit?: number,
5 page?: {
6 next?: string,
7 prev?: string
8 }
9}): Promise<{
10 page: {
11 next: string,
12 prev: string,
13 };
14 total: number,
15 status: number,
show all 17 lines

Input​

* required
ParameterDescription
filter
Type: string
Default:
n/a
Expression used to filter the results. Returns only these memberships whose properties satisfy the given expression. The filtering language is defined here.
sort
Type: object
Default:
n/a
Key-value pair of a property to sort by, and a sort direction. Available options are id, name, and updated. Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"}. By default, the items are sorted by the last updated date.
limit
Type: number
Default:
100
Number of objects to return in response. The default (and maximum) value is 100.
page
Type: object
Default:
n/a
Object used for pagination to define which previous or next result page you want to fetch.
> next
Type: string
Default:
n/a
Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
> prev
Type: string
Default:
n/a
Random string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. Ignored if the next parameter is supplied.

Output​

ParameterDescription
Promise<>
Type: object
Returned object containing these fields: page, total, status, and memberships.
> page
Type: any
Object used for pagination to define which previous or next result page you want to fetch.
>> next
Type: string
Random string returned from the server, indicating a specific position in a data set. Used for forward pagination, it fetches the next page, allowing you to continue from where you left off.
>> prev
Type: string
Random string returned from the server, indicating a specific position in a data set. Used for backward pagination, it fetches the previous page, enabling access to earlier data. Ignored if the next parameter is supplied.
> total
Type: number
Total number of channel memberships.
> status
Type: number
Status code of a server response, like 200.
> memberships
Type: Membership[]
List of all related memberships.

Sample code​

Find out which channels the support_agent_15 user is a member of.

1// reference the "support_agent_15" user
2const user = await chat.getUser("support_agent_15")
3
4// get the list of all user memberships
5await user.getMemberships()

Check membership​

Check whether a specific user is a member of a channel, or whether a user belongs to a specific channel.

Method signatures​

These methods take the following parameters:

  • channel.hasMember() — returns true if the given user is a member of the channel.

    1channel.hasMember(userId: string): Promise<boolean>
  • channel.getMember() — returns the Membership object for the given user on the channel, or null if not a member.

    1channel.getMember(userId: string): Promise<Membership | null>
  • user.isMemberOf() — returns true if the user is a member of the given channel.

    1user.isMemberOf(channelId: string): Promise<boolean>
  • user.getMembership() — returns the Membership object for the user on the given channel, or null if not a member.

    1user.getMembership(channelId: string): Promise<Membership | null>

Sample code​

Check whether a user is a member of a channel, and retrieve their membership details.

1// reference the "support" channel
2const channel = await chat.getChannel("support")
3
4// check if "support_agent_15" is a member of the channel
5const isMember = await channel.hasMember("support_agent_15")
6console.log("Is member:", isMember)
7
8// get the membership object for "support_agent_15"
9const membership = await channel.getMember("support_agent_15")
10if (membership) {
11 console.log("Membership:", membership)
12}
13
14// alternatively, check from the user's perspective
15const user = await chat.getUser("support_agent_15")
show all 23 lines

Get updates​

Receive updates when Membership objects are edited.

Event-based methods​

Use onUpdated() and onDeleted() to react to membership changes with callbacks:

1membership.onUpdated(callback: (membership: Membership) => void): () => void
2membership.onDeleted(callback: () => void): () => void

Sample code​

Listen for updates and deletions on the first user membership.

1const { memberships } = await chat.currentUser.getMemberships()
2const membership = memberships[0]
3
4const stopUpdated = membership.onUpdated((updatedMembership) => {
5 console.log("Membership updated:", updatedMembership)
6})
7
8const stopDeleted = membership.onDeleted(() => {
9 console.log("Membership was deleted")
10})
11
12// after some time...
13stopUpdated()
14stopDeleted()

Stream-based methods (deprecated)​

Deprecated

streamUpdates() is deprecated. Use onUpdated() and onDeleted() instead. streamUpdatesOn() remains supported.

  • streamUpdates() - monitors a single membership
  • streamUpdatesOn() - monitors multiple memberships
Membership changes

These methods notify about field changes (metadata, status) for existing memberships, not additions or removals.

Both methods accept a callback invoked when membership data changes. They subscribe to a channel and add an objects event listener for membership events, returning an unsubscribe function.

Stream update behavior
  • streamUpdates() returns the updated Membership object on each change (null if deleted)
  • streamUpdatesOn() returns the complete list of monitored memberships on any change
icon

Under the hood

Method signature​

These methods take the following parameters:

  • streamUpdates()

    1membership.streamUpdates(
    2 callback: (membership: Membership) => unknown
    3): () => void
  • streamUpdatesOn()

    1static Membership.streamUpdatesOn(
    2 memberships: Membership[],
    3 callback: (memberships: Membership[]) => unknown
    4): () => void

Input​

ParameterRequired in streamUpdates()Required in streamUpdatesOn()Description
memberships
Type: Membership[]
Default:
n/a
NoYesArray of Membership objects for which you want to get updates.
callback
Type: n/a
Default:
n/a
YesYesCallback function passed as a parameter to both methods. It defines the custom behavior to be executed when detecting membership changes.
> membership
Type: Membership
Default:
n/a
YesNoReturned Membership object with the updated data.
> memberships
Type: Membership[]
Default:
n/a
NoYesReturned array of Membership objects with the updated data.

Output​

TypeDescription
() => voidFunction you can call to disconnect (unsubscribe) from the channel and stop receiving objects events.

Errors​

Whenever a list of Membership objects is required as a parameter, and you try to get updates on membership without specifying their list, you will receive the Cannot stream membership updates on an empty list error.

Sample code​

Get updates on the first user membership.

  • streamUpdates()

    1const { memberships } = await chat.currentUser.getMemberships()
    2const membership = memberships[0]
    3membership.streamUpdates((membership) => {
    4 // The callback receives the entire updated Membership object each time a change occurs.
    5 if (membership) {
    6 console.log("Updated membership: ", membership)
    7 } else {
    8 console.log("Membership was deleted")
    9 }
    10})

Get updates on the first page of user memberships.

  • streamUpdatesOn()

    1const { memberships } = await chat.currentUser.getMemberships()
    2Membership.streamUpdatesOn(memberships, (memberships) => {
    3 // The callback receives the complete list of all memberships you're monitoring
    4 // each time any change occurs.
    5 console.log("Updated memberships: ", memberships)
    6})

Other examples​

Stop listening to updates on the first user membership.

  • streamUpdates()

    1const { memberships } = await chat.currentUser.getMemberships()
    2const membership = memberships[0]
    3const stopUpdates = membership.streamUpdates(/* handle update callback */)
    4// after some time...
    5stopUpdates()

Stop listening to updates on the first page of user memberships.

  • streamUpdatesOn()

    1const { memberships } = await chat.currentUser.getMemberships()
    2const stopUpdates = Membership.streamUpdatesOn(memberships, /* handle update callback */)
    3// after some time...
    4stopUpdates()

Delete membership​

Delete a user's channel membership with delete().

icon

Under the hood

Method signature​

This method has the following signature:

1membership.delete(): Promise<boolean>

Input​

This method doesn't take any parameters.

Output​

TypeDescription
Promise<boolean>Returns true when the membership is successfully deleted.

Sample code​

Delete the membership for the current user on the support channel.

1const channel = await chat.getChannel("support")
2const membership = await channel.join()
3
4const result = await membership.delete()
5console.log("Membership deleted:", result) // true

Update​

Update a user's channel membership information with update().

icon

Under the hood

Method signature​

This method takes the following parameters:

1membership.update({
2 status?: string,
3 type?: string,
4 custom?: ObjectCustom
5}): Promise<Membership>

Input​

* required
ParameterDescription
status
Type: string
Default:
n/a
Current status of the membership, like active or inactive.
type
Type: string
Default:
n/a
Type of the membership, used to categorize the user-channel relationship.
custom
Type: ObjectCustom
Default:
n/a
Any custom properties or metadata associated with the channel-user membership.

Output​

TypeDescription
Promise<Membership>Returned (modified) object containing all membership data.

Errors​

If you try to update a membership that doesn't exist, you will receive the No such membership exists error.

Sample code​

Assign the premium-support role to support_agent_15 on the high-priority-incidents channel.

1// reference the "support_agent_15" user
2const user = await chat.getUser("support_agent_15")
3
4// get the list of all user memberships and filter out the right channel
5const { memberships } = await user.getMemberships({
6 filter: "channel.id == 'high-priority-incidents'"
7})
8
9// add custom metadata to the user membership
10await memberships[0].update({
11 custom: {role: "premium-support"}
12})

Was this page useful?

Last updated on