On this page

Publish/Subscribe API for JavaScript SDK

PubNub's global publisher latency is approximately 2 ms for a publish request to be processed and acknowledged. Send a message to one recipient or broadcast to thousands of subscribers.

For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.

Supported and recommended asynchronous patterns

PubNub supports Callbacks, Promises, and Async/Await for asynchronous JS operations. The recommended pattern is Async/Await and all sample requests in this document are based on it. This pattern returns a status only on detecting an error. To receive the status errors, you must use the try...catch syntax in your code.

Publish

publish() sends a message to all channel subscribers. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel.

  • You must initialize PubNub with the publishKey.
  • You don't have to be subscribed to a channel to publish to it.
  • You cannot publish to multiple channels simultaneously.

Method(s)

To Publish a message, you can use the following method(s) in the JavaScript SDK:

1pubnub.publish({
2 message: any,
3 channel: string,
4 meta: any,
5 storeInHistory: boolean,
6 sendByPost: boolean,
7 ttl: number,
8 customMessageType: string
9}): Promise<PublishResponse>;
* required
ParameterDescription
message *
Type: any
Default:
n/a
The message may be any valid JSON type including objects, arrays, strings, and numbers.
channel *
Type: string
Default:
n/a
Specifies the channel ID to publish messages to.
storeInHistory
Type: boolean
Default:
true
If true the messages are stored in history.
If storeInHistory is not specified, then the history configuration on the key is used.
sendByPost
Type: boolean
Default:
false
When true, the SDK uses HTTP POST to publish the messages. The message is sent in the BODY of the request, instead of the query string when HTTP GET is used. Also the messages are compressed thus reducing the size of the messages. Using HTTP POST to publish messages adheres to RESTful API best practices.
meta
Type: any
Default:
n/a
Publish extra meta with the request.
ttl
Type: number
Default:
n/a
Set a per message time to live in Message Persistence.
  1. If storeInHistory = true, and ttl = 0, the message is stored with no expiry time.
  2. If storeInHistory = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours unless you have message retention set to Unlimited on your keyset configuration in the Admin Portal.
  3. If storeInHistory = false, the ttl parameter is ignored.
  4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
customMessageType
Type: string
Default:
n/a
A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.

Publish a message to a channel

1

1

Subscribe to the channel

Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.

Response

1type PublishResponse = {
2 timetoken: number
3}

Other examples

Publish a JSON-serialized message

1

Store the published message for 10 hours

1

Publish successful

1

Publish unsuccessful by network down

1

Publish unsuccessful by initialization without a publish key

1

Fire

The fire endpoint sends a message to Functions event handlers and Illuminate. The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via fire() aren't replicated to subscribers and aren't stored in history.

Method(s)

To Fire a message, you can use the following method(s) in the JavaScript SDK:

1fire({
2 Object message,
3 String channel,
4 Boolean sendByPost,
5 Object meta
6})
* required
ParameterDescription
message *
Type: Object
Default:
n/a
The message may be any valid JSON type including objects, arrays, strings, and numbers.
channel *
Type: String
Default:
n/a
Specifies channel ID to publish messages to.
sendByPost
Type: Boolean
Default:
false
If true the messages sent via POST.
meta
Type: Object
Default:
n/a
Publish extra meta with the request.

Sample code

Fire a message to a channel

1

Signal

The signal() function sends a signal to all subscribers of a channel.

By default, signals are limited to a message payload size of 64 bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.

Method(s)

To Signal a message, you can use the following method(s) in the JavaScript SDK:

1pubnub.signal({
2 message: string,
3 channel: string,
4 customMessageType: string,
5}): Promise<SignalResponse>;
* required
ParameterDescription
message *
Type: string
The message may be any valid JSON type including objects, arrays, strings, and numbers.
channel *
Type: string
Specifies channel ID to send messages to.
customMessageType
Type: string
A case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.

Sample code

Signal a message to a channel

1

Response

1type SignalResponse = {
2 timetoken: number
3}

Subscribe

The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified SDK entity or set of SDK entities. To subscribe successfully, configure the appropriate subscribeKey at initialization.

Conceptual overview

For more general information about subscriptions, refer to Subscriptions.

SDK entities are first-class citizens that provide access to their encapsulated APIs. You can subscribe using the PubNub client object or directly on a specific SDK entity:

A newly subscribed client receives messages after the subscribe() call completes. You can configure retryConfiguration to automatically attempt to reconnect and retrieve any available messages if a client gets disconnected.

Subscribe only opens the connection

Calling subscribe() opens a connection but doesn't deliver messages to your code. You must also add event listeners to receive messages and access sender information. The message object received through listeners includes the sender's ID in the publisher field.

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 client (for example, all subscriptions created on a single pubnub object). A set can include one or more subscriptions.

The event listener is a single point through which your app receives all the messages, signals, and events in the SDK entities you subscribed to. For information on adding event listeners, refer to Event listeners.

Add subscriptions to an existing set

If you subscribe to a subscription set and then add more subscriptions to it, they are automatically subscribed to.

Create a subscription

An entity-level subscription allows you to receive messages and events for only that SDK entity for which it was created. Using multiple entity-level subscriptions is useful for handling various message/event types differently in each channel.

1// SDK entity-based, local-scoped
2const channel = pubnub.channel('channel_1');
3channel.subscription(subscriptionOptions)
* required
ParameterDescription
subscriptionOptions
Type: subscriptionOptions
Subscription behavior configuration.

Create a subscription set

A client-level subscriptionSet allows you to receive messages and events for all SDK entities in the set. A single subscriptionSet is useful for similarly handling various message/event types in each channel.

1// client-based, general-scoped
2pubnub.subscriptionSet({
3 channels: string[],
4 channelGroups: string[],
5 subscriptionOptions: subscriptionOptions
6}))
* required
ParameterDescription
> channels
Type: string[]
Channels to subscribe to. Either channels or channelGroups is mandatory.
> channelGroups
Type: string[]
Channel groups to subscribe to. Either channels or channelGroups is mandatory.
> subscriptionOptions
Type: subscriptionOptions
Subscription behavior configuration.

subscriptionOptions

subscriptionOptions is a class. Available properties include:

OptionTypeDescription
receivePresenceEvents
boolean
Whether presence updates for userIds should be delivered through the listener streams.

For information on how to receive presence events and what those events are, refer to Presence Events.
cursor
object
Cursor from which to return any available cached messages. Message retrieval with cursor is not guaranteed and should only be considered a best-effort service. A cursor consists of a timetoken and region: cursor?: { timetoken?: string; region?: number }

If you pass any primitive type, the SDK converts them into SubscriptionCursor but if their value is not a 17-digit number or a string with numeric characters, the provided value will be ignored.

Modify a subscription set

You can add and remove subscriptions to and from an existing set to create new sets. If you subscribe to a subscription set and then add more subscriptions to it, they are automatically subscribed to.

Refer to the Other examples section for more information on adding and removing subscriptions.

Method(s)

subscription and subscriptionSet use the same subscribe() method.

Subscribe

To subscribe, you can use the following method in the JavaScript SDK:

1subscription.subscribe()
2subscriptionSet.subscribe()
Sample code
1

Wildcard subscribe and message objects

Wildcard subscribe (e.g., sports.*) works the same as regular subscribe - you still need to add event listeners to receive messages. The message objects received include the sender's ID in the publisher field, the actual channel name in the channel field, and the wildcard match in the subscription field.

Other examples
Create a subscription set from 2 individual subscriptions
1

Create a subscription set from 2 sets
1

Add subscriptions to an existing set
1

Returns

The subscribe() method doesn't have a return value.

SDK entities

SDK entities (also called entity handles) are subscribable objects for which you can receive real-time updates (messages, events, etc). An SDK entity is a local client-side handle: creating one performs no network call and does not require a matching server-side record to exist.

SDK entity is not the same as a DataSync entity

An SDK entity is the local handle described in this section. A DataSync entity is a stored server-side record, the source of truth for your application state, managed through the DataSync API. The DataSync SDK entities below are SDK entities that subscribe to DataSync entities.

Create channels

This method returns a local channel SDK entity.

1pubnub.channel(string)
* required
ParameterDescription
channel *
Type: string
The ID of the channel to create a subscription of.

Sample code

1

Create channel groups

This method returns a local channelGroup SDK entity.

1pubnub.channelGroup(string)
* required
ParameterDescription
channel_group *
Type: string
The name of the channel group to create a subscription of.

Sample code

1

Create channel metadata

This method returns a local channelMetadata SDK entity.

1pubnub.channelMetadata(string)
* required
ParameterDescription
channelMetadata *
Type: string
The String identifier of the channel metadata object to create a subscription of.

Sample code

1

Create user metadata

This method returns a local userMetadata SDK entity.

1pubnub.userMetadata(string)
* required
ParameterDescription
userMetadata *
Type: string
The String identifier of the user metadata object to create a subscription of.

Sample code

1

DataSync SDK entities

These methods return local SDK entities that subscribe to the real-time updates of a DataSync object. They are the subscribe-side counterpart to the pubnub.dataSync.* read and write methods, and subscribe is the only API they expose.

MethodObserves changes to
pubnub.dataSyncUser(id)
A DataSync user
pubnub.dataSyncChannel(id)
A DataSync channel
pubnub.dataSyncEntity(id)
A DataSync entity
pubnub.dataSyncRelationship(id)
A DataSync relationship
pubnub.dataSyncMembership(id)
A DataSync membership
* required
ParameterDescription
id *
Type: string
The identifier of the DataSync object to create a subscription of. Used verbatim, so a wildcard identifier such as product.* works as written.
Relationship and membership changes are not delivered on their own id

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. It is never published on a channel named after the relationship or membership id, so dataSyncRelationship(id) and dataSyncMembership(id) receive nothing for the link itself. To watch memberships appear and disappear, observe the linked user and channel with dataSyncUser and dataSyncChannel instead. Refer to Where each event is delivered.

Method(s)

1pubnub.dataSyncEntity(id: string)
2 .subscription({ projection: string, receivePresenceEvents: boolean, cursor: object, filter: function })

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

OptionTypeDescription
projection
string
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:

1const user = pubnub.dataSyncUser('user-alice')
2
3const base = user.subscription() // observes `user-alice`
4const admin = user.subscription({ projection: 'admin' }) // observes `__admin__user-alice`

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.

Identifiers are never rewritten

The identifier is passed 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

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1

Other examples

Observe every entity whose id matches a pattern

Because the identifier is used verbatim, a wildcard identifier subscribes to the matching channel pattern and one subscription serves the whole set. event.channel reports the concrete delivery channel, while event.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

A DataSync subscription is an ordinary subscription, so it composes into a set with any other subscription.

1

Event listeners

Messages and events are received in your app using a listener. This listener allows a single point to receive all messages, signals, and events.

You can attach listeners to the instances of subscription, subscriptionSet, and, in the case of the connection status, the PubNub client.

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

You can implement multiple listeners with the addListener() method or register an event-specific listener that receives only a selected type, like message or file.

Method(s)

1

Sample code

1

Message object contains sender information

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.

Add connection status listener

The PubNub client has a listener dedicated to handling connection status updates.

Client scope

This listener is only available on the PubNub object.

Method(s)

1

Sample code

1

Returns

The subscription status. For information about available statuses, refer to SDK statuses.

Add DataSync listener

DataSync publishes an event when an object (a user, channel, membership, or a custom entity or relationship) is created, updated, or deleted. To receive them, create a DataSync SDK entity for the object, subscribe to it, and attach a dataSync listener.

A create event for a user, channel, or entity is delivered only on its own id. An update or delete event for a user, channel, or entity is also delivered on the id of every entity, user, or channel connected to it by a relationship or membership. A membership or relationship event, on create, update, or delete alike, is delivered on the channels of both linked entities and never on a channel named after the membership or relationship id. Refer to Where each event is delivered for the full mapping.

The dataSync listener works on all three scopes: the PubNub client, a subscription, and a subscriptionSet.

Events are off by default

To receive DataSync events, enable event publishing for the object's class in the Admin Portal. Refer to DataSync events for details.

Events are filtered per projection

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

Method(s)

To receive DataSync events, attach a dataSync listener through any of the following attachment points:

1// On the client
2pubnub.addListener({ dataSync: (event) => { /* handle event */ } });
3pubnub.onDataSync = (event) => { /* handle event */ };
4
5// On a subscription or subscription set
6subscription.onDataSync = (event) => { /* handle event */ };

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

FieldTypeDescription
channel
string
The concrete data channel on which this copy of the event arrived. It can be 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
string | null
The subscription that matched, for example the wildcard pattern you subscribed to. null when it is the same as channel.
timetoken
string
The event timetoken.
message
object
The parsed DataSync change. Refer to the fields below.

The message object contains the change details:

FieldTypeDescription
version
string
The DataSync service payload version. May be absent.
event
string
The change type: create, update, or delete.
source
string
Always data-sync (hyphenated). This is the backend's wire-format value and differs intentionally from the dataSync naming used elsewhere in the SDK (the listener, onDataSync, and Access Manager resource key).
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
string
The normalized object kind, with the same five values as type. Against a current service it is identical to type. It differs only against an older service that reports the built-in classes under the generic entity or relationship kind, where the SDK derives the kind from className and classLevel instead. Read this one if you need to support both.
className
string
The class name of the changed object, as a plain name. May be absent.
classLevel
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
number
The class version of the changed object. May be absent.
data
object
The object state, which varies by event and type. Refer to the descriptions below.
note
Class identity lives on the event, not in data

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.

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
1

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, while the built-in classes report user, channel, and membership, so a filter hardcoded to entity silently drops every user and channel event.

For the fetch methods, refer to DataSync API. For the concurrency pattern, refer to the ETags concept documentation.

Unsubscribe

Stop receiving real-time updates from a subscription or a subscriptionSet.

Method(s)

1subscription.unsubscribe()
2
3subscriptionSet.unsubscribe()

Sample code

1

Returns

None

Unsubscribe all

Stop receiving real-time updates from all data streams and remove the SDK entities associated with them.

Client scope

This method is only available on the PubNub object.

Method(s)

1pubnub.unsubscribeAll()

Sample code

1

Returns

None

Subscribe (old)

Not recommended

The use of this method is discouraged. Use Subscribe instead.

Receive messages

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

For more information about adding a listener, refer to the Event Listeners section.

Description

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel ID the client must send the appropriate subscribeKey at initialization.

By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.

Connectivity notification

You can be notified of connectivity via the listener, on establishing connection the statusEvent.category returns PNConnectedCategory.

By waiting for the connect event to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Subscribe to a channel, you can use the following method(s) in the JavaScript SDK:

1pubnub.subscribe({
2 channels: Array<string>,
3 channelGroups: Array<string>,
4 withPresence: boolean,
5 timetoken: number
6}): Promise<SubscribeResponse>;
* required
ParameterDescription
channels *
Type: Array<string>
Default:
n/a
Specifies the channels to subscribe to. It is possible to specify multiple channels as a list or as an array.
channelGroups
Type: Array<string>
Default:
n/a
Specifies the channelGroups to subscribe to.
withPresence
Type: boolean
Default:
false
If true it also subscribes to presence instances.
timetoken
Type: number
Default:
n/a
Specifies timetoken from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service.

Sample code

Subscribe to a channel:

1

Event listeners

The response of the call is handled by adding a Listener. Please see the Event Listeners section for more details. Listeners should be added before calling the method.

Returns

The following objects will be returned in the status response
ObjectDescription
category
PNConnectedCategory
operation
PNSubscribeOperation
affectedChannels
The channels affected in the operation, of type array.
subscribedChannels
All the current subscribed channels, of type array.
affectedChannelGroups
The channel groups affected in the operation, of type array.
lastTimetoken
The last timetoken used in the subscribe request, of type long.
currentTimetoken
The current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
1{
2 category: 'PNConnectedCategory',
3 operation: 'PNSubscribeOperation',
4 affectedChannels: ['my_channel_1'],
5 subscribedChannels: ['my_channel_1'],
6 affectedChannelGroups: [],
7 lastTimetoken: '14974492380756600',
8 currentTimetoken: '14974492384874375'
9}
The following objects will be returned in the subscribe message response
ObjectDescription
channel
The channel ID for which the message belongs.
subscription
The channel group or wildcard subscription match (if exists).
timetoken
Publish timetoken.
message
The payload.
actualChannel
Deprecated. Use property channel.
subscribedChannel
Deprecated. Use property subscription.
1{
2 actualChannel: null,
3 channel: "my_channel_1",
4 message: "Hello World!",
5 publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
6 subscribedChannel: "my_channel_1",
7 subscription: null,
8 timetoken: "14966804541029440"
9}
The following objects will be returned in the Presence response
ObjectDescription
action
Can be join, leave, state-change or timeout.
channel
The channel ID for which the message belongs.
occupancy
No. of users connected with the channel ID.
state
User State.
subscription
The channel group or wildcard subscription match (if exists)
timestamp
Current timetoken.
timetoken
Publish timetoken.
uuid
UUIDs of users who are connected with the channel ID.
1{
2 category: 'PNConnectedCategory',
3 operation: 'PNSubscribeOperation',
4 affectedChannels: ['my_channel_1'],
5 subscribedChannels: ['my_channel_1'],
6 affectedChannelGroups: [],
7 lastTimetoken: '14974492380756600',
8 currentTimetoken: '14974492384874375'
9}

Other examples

Subscribing to multiple channels

It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.

Alternative subscription methods

You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.

1

Subscribing to a Presence channel
Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.

1

Wildcard subscribe to channels
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).

1

Wildcard grants and revokes

Only one level (a.*) of wildcarding is supported. If you grant on * or a.b.*, the grant will treat * or a.b.* as a single channel named either * or a.b.*. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*.

Subscribing with state
Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

For information on how to receive presence events and what those events are, refer to Presence Events.

Required UUID

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

1

Subscribe to a channel group
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Subscribe to the presence channel of a channel group
Requires Stream Controller and Presence add-ons

This method requires that both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Subscribing to multiple channel groups
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Subscribing to a channel and channel group simultaneously
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Sample Responses
Join event
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "join",
7 "timetoken": "15119466699655811",
8 "occupancy": 2,
9 "uuid": "User1",
10 "timestamp": 1511946669
11}
Leave event
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "leave",
7 "timetoken": "15119446002445794",
8 "occupancy": 1,
9 "uuid": "User1",
10 "timestamp": 1511944600
11}
Timeout event
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "timeout",
7 "timetoken": "15119519897494311",
8 "occupancy": 3,
9 "uuid": "User2",
10 "timestamp": 1511951989
11}
State change event
1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "state-change",
7 "state": {
8 "isTyping": true
9 },
10 "timetoken": "15119477895378127",
11 "occupancy": 5,
12 "uuid": "User4",
13 "timestamp": 1511947789
14}
Interval event
1{
2 "action": "interval",
3 "occupancy": 2,
4 "timestamp": 1511947739
5}

When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

  • joined
  • left
  • timedout

For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

1{
2 "action":"interval",
3 "timestamp":1548340678,
4 "occupancy":2,
5 "join":["pn-94bea6d1-2a9e-48d8-9758-f1b7162631ed","pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"]},
6 "timedout":["pn-cecbfbe3-312f-4928-93a2-5a79c91b10e0"],
7 "b":"my-channel-pnpres"
8}

If the full interval message is greater than 30 KB (since the max publish payload is ∼32 KiB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

1{
2 "channel": "my_channel",
3 "subscription": null,
4 "actualChannel": null,
5 "subscribedChannel": "my_channel-pnpres",
6 "action": "interval",
7 "timetoken": "15119477396210903",
8 "occupancy": 4,
9 "timestamp": 1511947739,
10 "here_now_refresh" : true
11}

You can be notified of connectivity status, message, and presence notifications via the listeners.

Listeners should be added before calling the method.

Add listeners

1pubnub.addListener({
2 // Messages
3 message: function (m) {
4 const channelName = m.channel; // Channel on which the message was published
5 const channelGroup = m.subscription; // Channel group or wildcard subscription match (if exists)
6 const pubTT = m.timetoken; // Publish timetoken
7 const msg = m.message; // Message payload
8 const publisher = m.publisher; // Message publisher
9 },
10 // Presence
11 // requires a subscription with presence
12 presence: function (p) {
13 const action = p.action; // Can be join, leave, timeout, state-change, or interval
14 const channelName = p.channel; // Channel to which the message belongs
15 const occupancy = p.occupancy; // Number of users subscribed to the channel
show all 72 lines

Remove listeners

1var existingListener = {
2 message: function () {
3 },
4};
5
6pubnub.removeListener(existingListener);
Listener status events
CategoryDescription
PNNetworkUpCategory
The SDK detected that the network is online.
PNNetworkDownCategory
The SDK announces this when a connection isn't available, or when the SDK isn't able to reach PubNub servers.
PNNetworkIssuesCategory
A subscribe event experienced an exception when running. The SDK isn't able to reach PubNub servers. This may be due to many reasons, such as the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy.
PNReconnectedCategory
The SDK was able to reconnect to PubNub.
PNConnectedCategory
SDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes.
PNAccessDeniedCategory
Access Manager permission failure.
PNMalformedResponseCategory
JSON parsing crashed.
PNBadRequestCategory
The server responded with a bad response error because the request is malformed.
PNDecryptionErrorCategory
If using decryption strategies and the decryption fails.
PNTimeoutCategory
Failure to establish a connection to PubNub due to a timeout.
PNRequestMessageCountExceedCategory
The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold.
PNUnknownCategory
Returned when the subscriber gets a non-200 HTTP response code from the server.

Unsubscribe (old)

Not recommended

The use of this method is discouraged. Use Unsubscribe instead.

When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Unsubscribe from a channel, you can use the following method(s) in the JavaScript SDK:

1pubnub.unsubscribe({
2 channels: Array<string>,
3 channelGroups: Array<string>
4}): Promise<UnsubscribeResponse>;
* required
ParameterDescription
channels *
Type: Array<string>
Specifies the channel ID to unsubscribe from.
channelGroups
Type: Array<string>
Specifies the channelGroups to unsubscribe from.

Sample code

Unsubscribe from a channel:

1

Response

The output below demonstrates the response to a successful call:

1{
2 "action" : "leave"
3}

Other examples

Unsubscribing from multiple channels
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Example response
1{
2 "action" : "leave"
3}
Unsubscribing from multiple channel groups
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

1

Unsubscribe all (old)

Not recommended

The use of this method is discouraged. Use Unsubscribe all instead.

Unsubscribe from all channels and all channel groups

Method(s)

1unsubscribeAll()

Sample code

1

Returns

None