About the Subscriber API

The Subscriber API lets clients subscribe to channels and resources to receive messages in real time. Subscribers with suitable permissions instantly receive messages sent by a publisher. Channels and resources are independent, so messages sent to a channel aren't delivered to a resource, and vice versa.

Learn more about the Realtime APIs.

With the Subscriber API, you can:

  • Subscribe or unsubscribe from a channel or resource.
  • Respond to subscription successes, connection errors, and incoming messages with dedicated handlers.

Subscription lifecycle

The subscribe() method returns a subscription ID immediately, but the connection is established in the background. Subscribers can use the subscription ID to unsubscribe at a later time.

You can register lifecycle handlers to respond when the subscription succeeds or fails:

Reconnection and message sync

If the connection drops, the client automatically attempts to reconnect and re-subscribe. When subscribing or re-subscribing, the isSynced parameter of the onSubscribed() handler indicates whether all missed messages were successfully restored, or whether the subscriber needs to take further action.

Learn more about subscribing to a channel or resource.

Subscription errors

Subscription errors occur when a subscription is rejected or when the connection fails. Each error includes errorCode and recoverable parameters that indicate the error type and whether the client is automatically trying to reconnect.

Learn more about how the subscribe() method handles subscription errors.

Unsubscribing

You can unsubscribe in the following ways:

  • By subscriptionId: Removes a single subscription.
  • By channel: Removes all subscriptions that match the specified channel and resource exactly. Unsubscribing from a channel doesn't affect subscriptions to resources on that channel, and vice versa.
  • By both: Removes the specific subscription, verifying it matches the specified channel or resource. If it doesn't, the subscription isn't removed.

When the last subscription on a connection is removed, the connection closes automatically.

Before you begin

It's important to note the following points before starting to code:

  • The Realtime SDK checks permissions when a subscription is first established. When a subscriber doesn't have read permission on the channel, the subscription fails.
  • Subscriptions don't persist across sessions. Closing a browser tab removes all its subscriptions.

See also

Did this help?