Subscribe API for JavaScript SDK

The Subscribe API lets a PubNub client for JavaScript receive messages and events in real time. You create a subscription for one SDK entity, or a subscription set for several, add an event listener, and then subscribe.

For the concepts behind publishing and subscribing, see Connection management, Subscriptions, and Publish messages.

Subscribe​

subscribe() starts receiving real-time messages and events for a subscription or subscription set of a PubNub client for JavaScript.

To subscribe, set subscribeKey when you create the PubNub client. See Initialization.

By default, a subscription receives the messages that PubNub publishes after the subscribe request completes.Calling subscribe() starts the subscription but delivers nothing to your code until you add an event listener.

A PubNub client for JavaScript retries failed subscribe requests as set by retryConfiguration. The setting applies when enableEventEngine is true, which is the default. See Configuration.

Calling subscribe() on a subscription or subscription set that is already subscribed has no effect.

Subscription scope​

Subscriptions let you attach listeners for specific real-time update types. Your app receives messages and events through those listeners. There are two types:

  • subscription: created from an SDK entity and scoped to that entity, for example a particular channel
  • subscriptionSet: created from the PubNub client and scoped to the channels, channel groups, and subscriptions that you put in the set

subscription and subscriptionSet use the same subscribe() method.

timetoken#
Type: string
Default: no default
The timetoken from which to start returning available cached messages. PubNub provides cached messages on a best-effort basis.

A wildcard channel name such as sports.* subscribes the same way. The message event reports the concrete channel in channel and the matching pattern in subscription.

Returns​

subscribe() returns nothing.

Syntax

1subscription.subscribe({ timetoken?: string }): void;
2subscriptionSet.subscribe({ timetoken?: string }): void;

Create a subscription​

subscription() creates a subscription for one SDK entity of a PubNub client for JavaScript. The subscription receives messages and events for only that entity.

Use several subscriptions to handle the message and event types of each channel differently.

subscriptionOptions#
Type: SubscriptionOptions
Default: no default
The options that control how the subscription behaves. See subscriptionOptions.

subscriptionOptions​

subscriptionOptions is an object of type SubscriptionOptions. Its properties are:

receivePresenceEvents#
Type: boolean
Default: false
Whether the subscription delivers presence events for the entity to its listeners. The option has an effect only for channel and channel group SDK entities. For the events and how to receive them, see Presence events.
filter#
Type: function
Default: no default
A function with the signature (event) => boolean that the SDK calls for each received event. The subscription passes the event to its listeners only when the function returns true.

Syntax

1channel.subscription(subscriptionOptions?: SubscriptionOptions): Subscription;

Create a subscription set​

subscriptionSet() creates a subscription set in a PubNub client for JavaScript. The set receives messages and events for all the SDK entities that it contains.

Use a subscription set to handle the message and event types of several channels in the same way.

channels#
Type: string[]
Default: no default
The IDs of the channels that the subscription set subscribes to. The set creates an SDK channel entity for each ID.
channelGroups#
Type: string[]
Default: no default
The names of the channel groups that the subscription set subscribes to. The set creates an SDK channel group entity for each name.
subscriptionOptions#
Type: SubscriptionOptions
Default: no default
The behavior options, described in subscriptionOptions. The set applies them to each subscription that it creates.

A set created with neither channels nor channelGroups starts empty. Add subscriptions to it later, as described in Modify a subscription set.

Syntax

1pubnub.subscriptionSet({
2 channels?: string[],
3 channelGroups?: string[],
4 subscriptionOptions?: SubscriptionOptions
5}): SubscriptionSet;

SDK entities​

An SDK entity is a local handle that represents something you can subscribe to in a PubNub client for JavaScript. Creating one performs no network call and needs no matching server-side record.

Every SDK entity has a subscription() method. The PubNub client returns the same SDK entity object when you call a creation method again with the same name or ID.

The client has a creation method for each kind of SDK entity:

An SDK entity is not a DataSync entity. A DataSync entity is a stored server-side record, the source of truth for your application state, which you manage through the DataSync API. The DataSync SDK entities are SDK entities that subscribe to DataSync entities.

Create an SDK channel entity​

channel() returns an SDK channel entity that represents a channel in a PubNub client for JavaScript.

required
name required#
Type: string
Default: no default
The ID of the channel to subscribe to. See channels.

Syntax

1pubnub.channel(name: string): Channel;

Create an SDK channel group entity​

channelGroup() returns an SDK channel group entity that represents a channel group in a PubNub client for JavaScript.

required
name required#
Type: string
Default: no default
The name of the channel group to subscribe to. See channel groups.

Syntax

1pubnub.channelGroup(name: string): ChannelGroup;

Create an SDK channel metadata entity​

channelMetadata() returns an SDK channel metadata entity that represents the App Context metadata of a channel in a PubNub client for JavaScript.

required
id required#
Type: string
Default: no default
The ID of the channel metadata object to observe. See channel metadata.

Syntax

1pubnub.channelMetadata(id: string): ChannelMetadata;

Create an SDK user metadata entity​

userMetadata() returns an SDK user metadata entity that represents the App Context metadata of a user in a PubNub client for JavaScript.

required
id required#
Type: string
Default: no default
The ID of the user metadata object to observe. See user metadata.

Syntax

1pubnub.userMetadata(id: string): UserMetadata;

Event listeners​

Event listeners are the single point through which your app receives all the messages, signals, and events of a PubNub client for JavaScript.

You can attach listeners to a subscription, a subscription set, and the PubNub client. A listener on the PubNub client receives the events of all its subscriptions. Attach the connection status listener to the PubNub client only. See Add connection status listener.

No built-in event throttling

The PubNub SDK delivers every incoming event to your listener as it arrives. There is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.

To reduce the number of messages delivered to your client in the first place, use Subscribe Filters to filter messages server-side before they reach your listener.

Add listeners​

addListener() adds an event listener that receives messages and events through a subscription, subscription set, or PubNub client for JavaScript.

You can also assign an event-specific handler that receives only one type of event, such as onMessage or onFile. Each assignment replaces the previous handler of that type.

required
listener required#
Type: Listener
Default: no default
An object whose properties are the handlers for each event type. Every handler is optional.
property of listener: message#
Type: function
Default: no default
Handles published messages.
property of listener: signal#
Type: function
Default: no default
Handles signals.
property of listener: presence#
Type: function
Default: no default
Handles presence events. A subscription delivers them when receivePresenceEvents is enabled.
property of listener: objects#
Type: function
Default: no default
Handles App Context events.
property of listener: messageAction#
Type: function
Default: no default
Handles message action events.
property of listener: file#
Type: function
Default: no default
Handles file sharing events.
property of listener: dataSync#
Type: function
Default: no default
Handles DataSync events. See Add DataSync listener.
property of listener: status#
Type: function
Default: no default
Handles connection status changes. Only the PubNub client reports connection status, so you cannot attach this listener to a subscription or subscription set. See Add connection status listener.

When you receive messages through listeners, the message object includes the sender's ID in the publisher field, along with the message content, channel name, timetoken, and other metadata.

Returns​

addListener() returns nothing.

Syntax

1subscription.addListener(listener: Listener): void;
2subscriptionSet.addListener(listener: Listener): void;
3pubnub.addListener(listener: Listener): void;

Add connection status listener​

addListener() adds a listener that reports the connection status of a PubNub client for JavaScript.

Only the PubNub client reports connection status, so you cannot attach this listener to a subscription or subscription set.
required
status required#
Type: function
Default: no default
The handler that the SDK calls each time the connection status changes, with the status object described under Returns.

Returns​

The handler receives a status object. Only category is always present. The other properties depend on the category. For the list of status categories, see SDK statuses.

category#
Type: string
The status category, for example PNConnectedCategory.
operation#
Type: string
The operation that reported the status.
error#
Type: string, boolean
Information about the error. The value is false when there is no error.
affectedChannels#
Type: string[]
The channels that the status change affects.
affectedChannelGroups#
Type: string[]
The channel groups that the status change affects.
subscribedChannels#
Type: string[]
The channels that the client is subscribed to now.
lastTimetoken#
Type: string, number
The timetoken that the previous subscribe request used.
currentTimetoken#
Type: string, number
The timetoken that the current subscribe request uses.
statusCode#
Type: number
The REST API status code. Present on statuses that report a failed request.
errorData#
Type: object
The error details that the REST API returned. Present on statuses that report a failed request.

Syntax

1pubnub.addListener({ status: (status: Status | StatusEvent) => void }): void;

Add DataSync listener​

dataSync is the listener for DataSync events, which a PubNub client for JavaScript gets when a DataSync object is created, updated, or deleted.

To receive these events, create a DataSync SDK entity for the object, subscribe to it, and attach a dataSync listener. The listener works on all three scopes: the PubNub client, a subscription, and a subscriptionSet.

DataSync events are off by default. You enable event publishing for each class in the Admin Portal. See enabling DataSync events.

A relationship or membership change is delivered on the ids of the two objects it links, and never on a channel named after the relationship or membership id. A create for a user, channel, or entity is delivered only on its own id. An update or delete for a user, channel, or entity is also delivered on the id of every object connected to it at the time of the change. The connection can be a relationship or membership, in either direction.

See Where each event is delivered for the full mapping.

An event is delivered once for each channel it fans out to, and each delivery carries only the fields that the channel's projection exposes. The plain (__default__) channel and a __{projection}__{id} channel each carry only the fields declared under their own projection. The service filters status the same way, through the class's declared projections for /status. The service always delivers id, eTag, createdAt, updatedAt, and expiresAt unfiltered and never filters delete events. See DataSync projections.

required
event required#
Type: DataSyncObject
Default: no default
The handler argument, which holds the event fields described below.

The listener callback receives an event object with the following properties:

channel#
Type: string
The concrete data channel on which this copy of the event arrived. The value is the changed object's ID, a connected entity's ID for a fanned-out event, or a named projection channel such as __admin__product-sneaker-42. Identify the changed object through message.data.id.
subscription#
Type: string | null
The subscription that matched, for example the wildcard pattern you subscribed to. null when it is the same as channel.
timetoken#
Type: string
The event timetoken.
message#
Type: object
The parsed DataSync change. Its properties are described below.

The message object contains the change details:

version#
Type: string
The DataSync service payload version. May be absent.
event#
Type: string
The change type: create, update, or delete.
source#
Type: string
Always data-sync (hyphenated), the wire-format value of the service. It differs from the dataSync naming used elsewhere in the SDK (the listener, onDataSync, and Access Manager resource key).
type#
Type: string
The object kind as sent by the service: user, channel, membership, entity, or relationship. The built-in User, Channel, and Membership classes report their own kind, and a class you define reports the generic entity or relationship.
objectType#
Type: string
The normalized object kind, with the same five values as type. Against a current service the value equals type. The two differ only against an older service that reports the built-in classes under the generic entity or relationship kind. In that case the SDK derives the kind from className and classLevel. Read this one if you need to support both.
className#
Type: string
The class name of the changed object, as a plain name. May be absent.
classLevel#
Type: string
Where the class is defined: Global for the built-in User, Channel, and Membership classes, or SubKey for a class you defined on your own key set. May be absent.
classVersion#
Type: number
The class version of the changed object. May be absent.
data#
Type: object
The object state, which varies by event and type. See the descriptions below.

className, classLevel, and classVersion are reported once on message and are not repeated inside data. There is no data.entityClass or data.relationshipClass on an event, unlike the objects returned by the DataSync API. Read classLevel alongside className when you need to tell a built-in class from one of your own that happens to share its name.

The shape of data depends on the object kind and the event:

  • Entity events (users, channels, and custom entities) on create and update carry the current object state: id, status, payload, createdAt, updatedAt, eTag, and expiresAt.
  • Relationship events (your own relationship classes) on create and update carry the same fields plus entityAId and entityBId.
  • Membership events on create and update carry the same fields plus channelId and userId, the same names the DataSync API uses. A membership event never carries entityAId or entityBId.
  • Delete events carry only id and deletedAt, for every object kind.

Apart from id, every data field can be absent, so guard the access when you read one, for example event.message.data.payload?.price.

To keep a full local copy of the object, fetch it once with pubnub.dataSync.getEntity() for the current state, then apply events as they arrive. Filter by type and data.id first because the channel also receives relationship and connected-entity fan-out. Compare the eTag or updatedAt on create and update events against your local copy to detect stale updates. Use id and deletedAt for delete events.

When you filter on type, match the value for the kind you are tracking. A class of your own reports entity or relationship. The built-in classes report user, channel, and membership. A filter hardcoded to entity therefore drops every user and channel event.

For the fetch methods, see the DataSync API. For the concurrency pattern, see ETags.

Syntax

1pubnub.addListener({ dataSync: (event: DataSyncObject) => void }): void;
2pubnub.onDataSync = (event: DataSyncObject) => void;
3subscription.onDataSync = (event: DataSyncObject) => void;
4subscriptionSet.onDataSync = (event: DataSyncObject) => void;

Remove listener​

removeListener() removes an event listener from a subscription, subscription set, or PubNub client for JavaScript, so the listener stops receiving events.

The SDK identifies a listener by object, so pass the same object that you passed to addListener(). Removing an object that you never added has no effect. The SDK counts additions, so call removeListener() once for each time that you added that object.

required
listener required#
Type: Listener
Default: no default
The listener object to remove. Pass the object that you passed to addListener().

Returns​

removeListener() returns nothing.

Syntax

1subscription.removeListener(listener: Listener): void;
2subscriptionSet.removeListener(listener: Listener): void;
3pubnub.removeListener(listener: Listener): void;

Remove all listeners​

removeAllListeners() removes every event listener from a subscription, subscription set, or PubNub client for JavaScript.

The call also clears the event-specific handlers that you assigned, such as onMessage. Subscriptions and subscription sets stay subscribed.

removeAllListeners() takes no parameters.

Returns​

removeAllListeners() returns nothing.

Syntax

1subscription.removeAllListeners(): void;
2subscriptionSet.removeAllListeners(): void;
3pubnub.removeAllListeners(): void;

Unsubscribe​

unsubscribe() stops a subscription or subscription set of a PubNub client for JavaScript from receiving real-time updates.

A channel stays subscribed while another active subscription or subscription set of the same PubNub client still uses it. If a subscription is subscribed only through a subscribed set, unsubscribe() on the subscription has no effect and the SDK logs a warning. Remove the subscription from the set instead.

unsubscribe() takes no parameters.

Returns​

unsubscribe() returns nothing.

Syntax

1subscription.unsubscribe(): void;
2subscriptionSet.unsubscribe(): void;

Unsubscribe all​

unsubscribeAll() unsubscribes every subscription and subscription set of a PubNub client for JavaScript at once.

Only the PubNub client has this method, not a subscription or subscription set.

unsubscribeAll() takes no parameters.

Returns​

unsubscribeAll() returns nothing.

Syntax

1pubnub.unsubscribeAll(): void;

Create a subscription set from subscriptions​

subscription.addSubscription() combines two subscriptions into a new subscription set in a PubNub client for JavaScript.

The new set contains both subscriptions. If either subscription is already subscribed, the new set subscribes immediately.

required
subscription required#
Type: Subscription
Default: no default
The subscription to combine with the receiver into a new set.

Syntax

1subscription.addSubscription(subscription: Subscription): SubscriptionSet;

Modify a subscription set​

addSubscriptions() and removeSubscriptions() change the subscriptions in a subscription set of a PubNub client for JavaScript.

If the subscription set is already subscribed, a change takes effect immediately.

required
subscription required#
Type: Subscription
Default: no default
The subscription to add to or remove from the set.
subscriptions required#
Type: Subscription[]
Default: no default
The subscriptions to add to or remove from the set.

Syntax

1subscriptionSet.addSubscription(subscription: Subscription): void;
2subscriptionSet.addSubscriptions(subscriptions: Subscription[]): void;
3subscriptionSet.removeSubscription(subscription: Subscription): void;
4subscriptionSet.removeSubscriptions(subscriptions: Subscription[]): void;

Combine subscription sets​

addSubscriptionSet() and removeSubscriptionSet() merge another subscription set into a subscription set of a PubNub client for JavaScript, or remove it again.

required
subscriptionSet required#
Type: SubscriptionSet
Default: no default
The subscription set whose subscriptions the receiver adds or removes.

Syntax

1subscriptionSet.addSubscriptionSet(subscriptionSet: SubscriptionSet): void;
2subscriptionSet.removeSubscriptionSet(subscriptionSet: SubscriptionSet): void;

DataSync SDK entities​

dataSyncEntity() and the other DataSync entity methods return SDK entities that observe DataSync objects in a PubNub client for JavaScript.

These methods are the subscribe-side counterpart to the pubnub.dataSync.* read and write methods. Call subscription() on the returned SDK entity to observe changes. Each method observes one kind of DataSync object:

  • dataSyncUser(): a DataSync user
  • dataSyncChannel(): a DataSync channel
  • dataSyncEntity(): a DataSync entity
  • dataSyncRelationship(): a DataSync relationship
  • dataSyncMembership(): a DataSync membership

A relationship change is delivered on the data channels of the two entities it links (entityAId and entityBId), and a membership change on those of its userId and channelId. The service never publishes either on a channel named after the relationship or membership id, so dataSyncRelationship() and dataSyncMembership() receive nothing for the link itself. To watch memberships appear and disappear, observe the linked user and channel with dataSyncUser() and dataSyncChannel() instead. See Where each event is delivered.

required
id required#
Type: string
Default: no default
The ID of the DataSync object to observe. The SDK uses it verbatim, so a wildcard identifier such as product.* works as written.

DataSync SDK entities accept every subscriptionOptions property plus one of their own, projection:

subscriptionOptions#
Type: DataSyncSubscriptionOptions
Default: no default
The subscription options, with the extra projection property.
property of subscriptionOptions: projection#
Type: string
Default: no default
The name of the DataSync projection to observe. Omit it, or pass default or __default__, to observe the object itself. Any other name observes the projection on its own __{projection}__{id} channel.

receivePresenceEvents is ignored, because a DataSync object is observed on a single data channel and has no presence channel.

The projection is chosen per subscription rather than per entity, so one entity can serve several projections at once. Each (id, projection) pair is subscribed and unsubscribed independently:

Both subscriptions receive their own copy of a change, and the projected one carries whatever extra fields the admin projection exposes. Unsubscribing one leaves the other subscribed.

The SDK passes the identifier through exactly as given. dataSyncUser('__admin__u1').subscription({ projection: 'admin' }) therefore observes __admin____admin__u1, and the SDK does not collapse the repeated prefix.

Syntax

1pubnub.dataSyncUser(id: string): DataSyncUser;
2pubnub.dataSyncChannel(id: string): DataSyncChannel;
3pubnub.dataSyncEntity(id: string): DataSyncEntity;
4pubnub.dataSyncRelationship(id: string): DataSyncRelationship;
5pubnub.dataSyncMembership(id: string): DataSyncMembership;

Deprecated subscribe methods​

Deprecated JavaScript subscribe methods still work, and each one has a current replacement.

The pubnub.subscribe(), pubnub.unsubscribe(), and pubnub.unsubscribeAll() methods that take channels and channelGroups are discouraged for new apps. Use Subscribe, Unsubscribe, and Unsubscribe all instead. The reference for apps that still use them is Subscribe API: not recommended methods for JavaScript SDK.

Was this page useful?

Last updated on