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.
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 channelsubscriptionSet: 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#- 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.
Sample code
Returns
subscribe() returns nothing.
Examples for Subscribe
Syntax
1subscription.subscribe({ timetoken?: string }): void;
2subscriptionSet.subscribe({ timetoken?: string }): void;
Basic usage
1
Basic usage (React)
In React, create the subscription inside a useEffect hook and unsubscribe in the cleanup function to avoid memory leaks when the component unmounts.
1
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#- The options that control how the subscription behaves. See
subscriptionOptions.
subscriptionOptions
subscriptionOptions is an object of type SubscriptionOptions. Its properties are:
receivePresenceEvents#- 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#- A function with the signature
(event) => booleanthat the SDK calls for each received event. The subscription passes the event to its listeners only when the function returnstrue.
Sample code
Examples for Create a subscription
Syntax
1channel.subscription(subscriptionOptions?: SubscriptionOptions): Subscription;
Basic usage
1
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#- The IDs of the channels that the subscription set subscribes to. The set creates an SDK channel entity for each ID.
channelGroups#- The names of the channel groups that the subscription set subscribes to. The set creates an SDK channel group entity for each name.
subscriptionOptions#- 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.
Examples for Create 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:
channelchannelGroupuserMetadatachannelMetadatadataSyncUser,dataSyncChannel,dataSyncEntity,dataSyncRelationship, anddataSyncMembership
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.
Sample code
Examples for Create an SDK channel entity
Syntax
1pubnub.channel(name: string): Channel;
Basic usage
1
Create an SDK channel group entity
channelGroup() returns an SDK channel group entity that represents a channel group in a PubNub client for JavaScript.
namerequired#- The name of the channel group to subscribe to. See channel groups.
Sample code
Examples for Create an SDK channel group entity
Syntax
1pubnub.channelGroup(name: string): ChannelGroup;
Basic usage
1
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.
idrequired#- The ID of the channel metadata object to observe. See channel metadata.
Sample code
Examples for Create an SDK channel metadata entity
Syntax
1pubnub.channelMetadata(id: string): ChannelMetadata;
Basic usage
1
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.
idrequired#- The ID of the user metadata object to observe. See user metadata.
Sample code
Examples for Create an SDK user metadata entity
Syntax
1pubnub.userMetadata(id: string): UserMetadata;
Basic usage
1
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.
listenerrequired#- An object whose properties are the handlers for each event type. Every handler is optional.
- property of listener:
message# - Handles published messages.
- property of listener:
signal# - Handles signals.
- property of listener:
presence# - Handles presence events. A subscription delivers them when
receivePresenceEventsis enabled. - property of listener:
objects# - Handles App Context events.
- property of listener:
messageAction# - Handles message action events.
- property of listener:
file# - Handles file sharing events.
- property of listener:
dataSync# - Handles DataSync events. See Add DataSync listener.
- property of listener:
status# - 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.
Sample code
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.
Examples for Add listeners
Syntax
1subscription.addListener(listener: Listener): void;
2subscriptionSet.addListener(listener: Listener): void;
3pubnub.addListener(listener: Listener): void;
Basic usage
1
1
Basic usage (React)
In React, add listeners inside useEffect and remove them in the cleanup function. Update component state from within the listener callbacks to trigger re-renders.
1
Add connection status listener
addListener() adds a listener that reports the connection status of a PubNub client for JavaScript.
statusrequired#- The handler that the SDK calls each time the connection status changes, with the status object described under Returns.
Sample code
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#- The status category, for example
PNConnectedCategory. operation#- The operation that reported the status.
error#- Information about the error. The value is
falsewhen there is no error. affectedChannels#- The channels that the status change affects.
affectedChannelGroups#- The channel groups that the status change affects.
subscribedChannels#- The channels that the client is subscribed to now.
lastTimetoken#- The timetoken that the previous subscribe request used.
currentTimetoken#- The timetoken that the current subscribe request uses.
statusCode#- The REST API status code. Present on statuses that report a failed request.
errorData#- The error details that the REST API returned. Present on statuses that report a failed request.
Examples for Add connection status listener
Syntax
1pubnub.addListener({ status: (status: Status | StatusEvent) => void }): void;
Basic usage
1
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.
eventrequired#- The handler argument, which holds the event fields described below.
The listener callback receives an event object with the following properties:
channel#- 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 throughmessage.data.id. subscription#- The subscription that matched, for example the wildcard pattern you subscribed to.
nullwhen it is the same aschannel. timetoken#- The event timetoken.
message#- The parsed DataSync change. Its properties are described below.
The message object contains the change details:
version#- The DataSync service payload version. May be absent.
event#- The change type:
create,update, ordelete. source#- Always
data-sync(hyphenated), the wire-format value of the service. It differs from thedataSyncnaming used elsewhere in the SDK (the listener,onDataSync, and Access Manager resource key). type#- The object kind as sent by the service:
user,channel,membership,entity, orrelationship. The built-inUser,Channel, andMembershipclasses report their own kind, and a class you define reports the genericentityorrelationship. objectType#- The normalized object kind, with the same five values as
type. Against a current service the value equalstype. The two differ only against an older service that reports the built-in classes under the genericentityorrelationshipkind. In that case the SDK derives the kind fromclassNameandclassLevel. Read this one if you need to support both. className#- The class name of the changed object, as a plain name. May be absent.
classLevel#- Where the class is defined:
Globalfor the built-inUser,Channel, andMembershipclasses, orSubKeyfor a class you defined on your own key set. May be absent. classVersion#- The class version of the changed object. May be absent.
data#- 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
createandupdatecarry the current object state:id,status,payload,createdAt,updatedAt,eTag, andexpiresAt. - Relationship events (your own relationship classes) on
createandupdatecarry the same fields plusentityAIdandentityBId. - Membership events on
createandupdatecarry the same fields pluschannelIdanduserId, the same names the DataSync API uses. A membership event never carriesentityAIdorentityBId. - Delete events carry only
idanddeletedAt, 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.
Sample code
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.
Examples for Add DataSync listener
Syntax
1pubnub.addListener({ dataSync: (event: DataSyncObject) => void }): void;
2pubnub.onDataSync = (event: DataSyncObject) => void;
3subscription.onDataSync = (event: DataSyncObject) => void;
4subscriptionSet.onDataSync = (event: DataSyncObject) => void;
Basic usage
1
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.
listenerrequired#- The listener object to remove. Pass the object that you passed to
addListener().
Returns
removeListener() returns nothing.
Examples for Remove listener
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.
Examples for Remove all listeners
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.
Sample code
Returns
unsubscribe() returns nothing.
Examples for Unsubscribe
Syntax
1subscription.unsubscribe(): void;
2subscriptionSet.unsubscribe(): void;
Basic usage
1
Unsubscribe all
unsubscribeAll() unsubscribes every subscription and subscription set of a PubNub client for JavaScript at once.
unsubscribeAll() takes no parameters.
Sample code
Returns
unsubscribeAll() returns nothing.
Examples for Unsubscribe all
Syntax
1pubnub.unsubscribeAll(): void;
Basic usage
1
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.
subscriptionrequired#- The subscription to combine with the receiver into a new set.
Sample code
Examples for Create a subscription set from subscriptions
Syntax
1subscription.addSubscription(subscription: Subscription): SubscriptionSet;
Basic usage
1
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.
Sample code
Examples for Modify a subscription set
Syntax
1subscriptionSet.addSubscription(subscription: Subscription): void;
2subscriptionSet.addSubscriptions(subscriptions: Subscription[]): void;
3subscriptionSet.removeSubscription(subscription: Subscription): void;
4subscriptionSet.removeSubscriptions(subscriptions: Subscription[]): void;
Basic usage
1
Combine subscription sets
addSubscriptionSet() and removeSubscriptionSet() merge another subscription set into a subscription set of a PubNub client for JavaScript, or remove it again.
subscriptionSetrequired#- The subscription set whose subscriptions the receiver adds or removes.
Sample code
Examples for Combine subscription sets
Syntax
1subscriptionSet.addSubscriptionSet(subscriptionSet: SubscriptionSet): void;
2subscriptionSet.removeSubscriptionSet(subscriptionSet: SubscriptionSet): void;
Basic usage
1
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 userdataSyncChannel(): a DataSync channeldataSyncEntity(): a DataSync entitydataSyncRelationship(): a DataSync relationshipdataSyncMembership(): 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.
idrequired#- 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#- The subscription options, with the extra
projectionproperty. - property of subscriptionOptions:
projection# - The name of the DataSync projection to observe. Omit it, or pass
defaultor__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.
Sample code
Other examples
Examples for DataSync SDK entities
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;
Syntax (2)
1dataSyncEntity.subscription(subscriptionOptions?: DataSyncSubscriptionOptions): Subscription;
Syntax (3)
1
Basic usage
1
Observe every entity whose id matches a pattern
Observe every entity whose id matches a pattern
The SDK uses the identifier verbatim, so a wildcard identifier subscribes to the matching channel pattern and one subscription serves the whole set. In the event, channel reports the concrete delivery channel, while subscription reports the pattern that matched it. For a fanned-out event, the changed object's id can differ from the delivery channel, so identify it through event.message.data.id.
1
Combine DataSync subscriptions with other subscriptions
Combine DataSync subscriptions with other subscriptions
A DataSync subscription is an ordinary subscription, so it composes into a set with any other subscription.
1
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.