Channel group events

A channel group lets a client subscribe to many channels as one unit, while your server decides which channels the group holds. Adding or removing channels in a channel group server-side changes what every subscribed client receives without any client resubscribing. This page covers a pattern that gives each group a default events channel. Your server publishes to it, so subscribed clients know when the group changes. For how many channels a group holds and how many groups a client can subscribe to, refer to Subscribe limits.

Keep a default channel in every group​

A subscribe to an empty channel group fails with a 400 Bad Request error. Add a default channel when you create the group, and never remove it. The group then always holds at least one channel, and the default channel can carry events about the group. Name it after the group, for example <group>-events.

Events your server can publish​

An event can be anything your app needs. These are a useful start:

EventWhen your server publishes it
Channels addedAfter it adds channels to the group. The message lists the channels.
Channels removedAfter it removes channels from the group. The message lists the channels.
Group fullWhen adding channels fails because the group reached its channel limit.
Group emptyWhen only the default channel is left in the group.
Group deletedBefore it deletes the group, so clients can unsubscribe and clean up.

Don't publish an event when you add or remove the default channel itself, because no client listens to it at that moment. Your users don't have to see these events. They let your app react in the background.

Publish events from your server​

Only your server adds and removes channels. A channel group's manage permission lets whoever holds it add or remove any channel in that group, so grant manage only to server-side tokens. The server code that changes the group can also publish the event, which keeps all the logic in one place.

This JavaScript example adds channels to a group and then publishes the event:

async function addChannels(channelGroup, channels) {
await pubnub.channelGroups.addChannels({ channelGroup, channels });
await pubnub.publish({
channel: `${channelGroup}-events`,
message: { action: 'add', channels },
});
}

Was this page useful?

Last updated on