Publish/Subscribe API for PubNub JavaScript SDK

The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.

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

The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.

Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.

Publish Anytime

It's not required to be subscribed to a channel in order to publish to that channel.

Message Data

The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data should not contain special JavaScript classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.

Don't use JSON.stringify

It is important to note that you should not use JSON.stringify() when sending signals/messages via PubNub. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.

Message Size

The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.

If the message you publish exceeds the configured size, you will receive the following message:

Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details, check the support article.

Message Publish Rate

Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

Publishing to Multiple Channels

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

Publishing Messages Reliably

There are some best practices to ensure messages are delivered when publishing to a channel:

  • Publish to any given channel in a serial manner (not concurrently).
  • Check that the return code is success (for example, [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs for example Publish no faster than 5 msgs per second to any one channel.

Method(s)

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

pubnub.publish({
message: any,
channel: string,
meta: any,
storeInHistory: boolean,
sendByPost: boolean,
ttl: number
}): Promise<PublishResponse>;
ParameterTypeRequiredDefaultDescription
Operation ArgumentsHashYesA hash of arguments.
messageanyYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
channelstringYesSpecifies channel name to publish messages to.
storeInHistorybooleanOptionaltrueIf true the messages are stored in history.
If storeInHistory is not specified, then the history configuration on the key is used.
sendByPostbooleanOptionalfalseWhen 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.
metaanyOptionalPublish extra meta with the request.
ttlnumberOptionalSet 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.
  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.

Basic Usage

Publish a message to a channel

try {
const result = await pubnub.publish({
message: {
such: "object",
},
channel: "my_channel",
sendByPost: false, // true to send via post
storeInHistory: false, //override default Message Persistence options
meta: {
cool: "meta",
}, // publish extra meta with the request
});
} catch (status) {
console.log(status);
}
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

type PublishResponse = {
timetoken: number
}

Other Examples

Publish a JSON serialized message

const newMessage = {
text: "Hi There!",
};

try {
const result = await pubnub.publish({
message: newMessage,
channel: "my_channel",
});

console.log("message published w/ server response: ", result);
} catch (status) {
console.log("publishing failed w/ status: ", status);
}

Store the published message for 10 hours

try {
const result = await pubnub.publish({
message: "hello!",
channel: "my_channel",
storeInHistory: true,
ttl: 10,
});

console.log("message published w/ server response: ", response);
} catch (status) {
console.log("publishing failed w/ status: ", status);
}

Publish successful

const result = await pubnub.publish({
message: "hello world!",
channel: "ch1",
});

console.log(response); // {timetoken: "14920301569575101"}

Publish unsuccessful by network down

try {
const result = await pubnub.publish({
message: "hello world!",
channel: "ch1",
});
} catch (status) {
console.log(status); // {error: true, operation: "PNPublishOperation", errorData: Error, category: "PNNetworkIssuesCategory"}
}

Publish unsuccessful by initialization without publishKey

try {
const result = await pubnub.publish({
message: "hello world!",
channel: "ch1",
});
} catch (status) {
console.log(status); // {error: true, operation: "PNPublishOperation", statusCode: 400, errorData: Error, category: "PNBadRequestCategory"}
}

Publish unsuccessful by missing channel

try {
const result = await pubnub.publish({
message: "hello world!",
});
} catch (status) {
console.log(status); // {message: "Missing Channel", type: "validationError", error: true}
}

Publish unsuccessful by missing message

try {
const result = await pubnub.publish({
channel: "ch1",
});
} catch (status) {
console.log(status); // {message: "Missing Message", type: "validationError", error: true}
}

Fire

The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.

Method(s)

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

fire({
Object message,
String channel,
Boolean sendByPost,
Object meta
})
ParameterTypeRequiredDefaultDescription
Operation ArgumentsHashYesA hash of arguments.
messageObjectYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
channelStringYesSpecifies channel name to publish messages to.
sendByPostBooleanOptionalfalseIf true the messages sent via POST.
metaObjectOptionalPublish extra meta with the request.

Basic Usage

Fire a message to a channel

try {
const result = await pubnub.fire({
message: {
such: "object",
},
channel: "my_channel",
sendByPost: false, // true to send via post
meta: {
cool: "meta",
}, // fire extra meta with the request
});

console.log("message published w/ timetoken", response.timetoken);
} catch (status) {
// handle error
show all 17 lines

Other Examples

Basic usage with Promises

pubnub.fire({
message: {
such: 'object'
},
channel: 'my_channel',
sendByPost: false, // true to send via post
meta: {
"cool": "meta"
} // fire extra meta with the request
}).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});

Signal

The signal() function is used to send 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:

pubnub.signal({
message: string,
channel: string
}): Promise<SignalResponse>;
ParameterTypeRequiredDescription
Operation ArgumentsHashYesA hash of arguments.
messagestringYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
channelstringYesSpecifies channel name to send messages to.

Basic Usage

Signal a message to a channel

const result = await pubnub.signal({
message: "hello",
channel: "foo",
});

Response

type SignalResponse = {
timetoken: number
}

Subscribe

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

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 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.

Subscription scope

Subscription objects provide an interface to attach listeners for various real-time update types. Your app receives messages and events via those event listeners. Two types of subscriptions are available:

  • subscription, created from an entity with a scope of only that entity (for example, a particular channel)
  • subscriptionSet, created from the PubNub client with a global scope (for example, all subscriptions created on a single pubnub object ). A subscription set can have one or more subscriptions.

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

Create a subscription

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

// entity-based, local-scoped
const channel = pubnub.channel('channel_1');
channel.subscription(subscriptionOptions)
ParameterTypeRequiredDescription
subscriptionOptionssubscriptionOptionsNoSubscription behavior configuration.

Create a subscription set

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

// client-based, general-scoped
pubnub.subscriptionSet({
channels: string[],
channelGroups: string[],
subscriptionOptions: subscriptionOptions
}))
ParameterTypeRequiredDescription
 → channelsstring[]NoChannels to subscribe to. Either channels or channelGroups is mandatory.
 → channelGroupsstring[]NoChannel groups to subscribe to. Either channels or channelGroups is mandatory.
 → subscriptionOptionssubscriptionOptionsNoSubscription behavior configuration.
Add/remove sets

You can add and remove subscription sets to create new sets. Refer to the Other examples section for more information.

subscriptionOptions

subscriptionOptions is a class. Available properties include:

OptionTypeDescription
receivePresenceEventsbooleanWhether presence updates for userId should be delivered through the listener streams.
cursorobjectCursor 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.

Method(s)

subscription and subscriptionSet use the same subscribe() method.

Subscribe

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

subscription.subscribe()
subscriptionSet.subscribe()
Basic usage
const subscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] });
subscriptionSet.subscribe();
Other examples
Create a subscription set from 2 individual subscriptions
// create a subscription from a channel entity
const channel = pubnub.channel('channel_1')
const subscription1 = channel.subscription({ receivePresenceEvents: true });

// create a subscription from a channel group entity
const channelGroup = pubnub.channelGroup('channelGroup_1')
const subscription2 = channelGroup.subscription();

// add 2 subscriptions to create a subscription set
const subscriptionSet = subscription1.addSubscription(subscription2);

// add another subscription to the set
const subscription3 = pubnub.channel('channel_3').subscription({ receivePresenceEvents: false });
subscriptionSet.addSubscription(subscription3);

show all 19 lines
Create a subscription set from 2 sets
// create a subscription set with multiple channels
const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] });

// create a subscription set with multiple channel groups and options
const subscriptionSet2 = pubnub.subscriptionSet({
channels: ['ch1', 'ch2'],
subscriptionOptions: { receivePresenceEvents: true }
});

// create a new subscription set from 2 sets
const subscriptionSet3 = subscriptionSet1.addSubscriptionSet(subscriptionSet2);

// you can also remove sets
const subscriptionSetWithChannelsOnly = subscriptionSet3.removeSubscriptionSet(subscriptionSet2);
Returns

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

Entities

Entities are subscribable objects for which you can receive real-time updates (messages, events, etc).

Create channels

This method returns a local channel entity.

pubnub.channel(string)
ParameterTypeRequiredDescription
channelstringYesThe name of the channel to create a subscription of.

Basic usage

const channel = pubnub.channel('channel_1');

Create channel groups

This method returns a local channelGroup entity.

pubnub.channelGroup(string)
ParameterTypeRequiredDescription
channel_groupstringYesThe name of the channel group to create a subscription of.

Basic usage

const channelGroup = pubnub.channelGroup('channelGroup_1');

Create channel metadata

This method returns a local channelMetadata entity.

pubnub.channelMetadata(string)
ParameterTypeRequiredDescription
channelMetadatastringYesThe String identifier of the channel metadata object to create a subscription of.

Basic usage

const channelMetadata = pubnub.channelMetadata('channel_1');

Create user metadata

This method returns a local userMetadata entity.

pubnub.userMetadata(string)
ParameterTypeRequiredDescription
userMetadatastringYesThe String identifier of the user metadata object to create a subscription of.

Basic usage

const userMetadata = pubnub.userMetadata('user_meta1');

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.

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)

// create a subscription from a channel entity
const channel = pubnub.channel('channel_1');
const subscription = channel.subscription();

// Event-specific listeners
subscription.onMessage = (messageEvent) => { console.log("Message event: ", messageEvent); };
subscription.onPresence = (presenceEvent) => { console.log("Presence event: ", presenceEvent); };
subscription.onMessage = (messageEvent) => { console.log("Message event: ", messageEvent); };
subscription.onPresence = (presenceEvent) => { console.log("Presence event: ", presenceEvent); };
subscription.onSignal = (signalEvent) => { console.log("Signal event: ", signalEvent); };
subscription.onObjects = (objectsEvent) => { console.log("Objects event: ", objectsEvent); };
subscription.onMessageAction = (messageActionEvent) => { console.log("Message Action event: ", messageActionEvent); };
subscription.onFile = (fileEvent) => { console.log("File event: ", fileEvent); };

// Generic listeners
show all 77 lines

Basic usage

// create a subscription from a channel entity
const channel = pubnub.channel('channel_1')
const subscription1 = channel.subscription({ receivePresenceEvents: true });

// create a subscription set with multiple channels
const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] });

// add a status listener
pubnub.addListener({
status: (s) => {console.log('Status', s.category) }
});

// add message and presence listeners
subscription1.addListener({
// Messages
show all 27 lines

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)

pubnub.addListener({
status: (s) => s.category
})

Basic usage

// add a status listener
pubnub.addListener({
status: (s) => {console.log('Status', s.category) }
});

Returns

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

Unsubscribe

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

Method(s)

subscription.unsubscribe()

subscriptionSet.unsubscribe()

Basic Usage

// create a subscription from a channel entity
const channel = pubnub.channel('channel_1')
const subscription1 = channel.subscription({ receivePresenceEvents: true });

// create a subscription set with multiple channels
const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] });

subscription1.subscribe();
subscriptionSet1.subscribe();

subscription1.unsubscribe();
subscriptionSet1.unsubscribe();

Returns

None

Unsubscribe All

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

Client scope

This method is only available on the PubNub object.

Method(s)

pubnub.unsubscribeAll()

Basic Usage

// create a subscription set with multiple channels
const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] });
subscriptionSet1.subscribe();

// create a subscription from a channel entity
const channelGroup = pubnub.channelGroup('channelGroup_1')
const subscription1 = channelGroup.subscription({ receivePresenceEvents: true });
subscription1.subscribe();

pubnub.unsubscribeAll();

Returns

None

Subscribe (deprecated)

Deprecated

This method is deprecated. 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 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:

pubnub.subscribe({
channels: Array<string>,
channelGroups: Array<string>,
withPresence: boolean,
timetoken: number
}): Promise<SubscribeResponse>;
ParameterTypeRequiredDefaultDescription
Operation ArgumentsHashYesA hash of arguments.
channelsArray<string>YesSpecifies the channels to subscribe to. It is possible to specify multiple channels as a list or as an array.
channelGroupsArray<string>Specifying either channels or channelGroups is mandatorySpecifies the channelGroups to subscribe to.
withPresencebooleanOptionalfalseIf true it also subscribes to presence instances.
timetokennumberOptionalSpecifies 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.

Basic Usage

Subscribe to a channel:

pubnub.subscribe({
channels: ["my_channel"],
});
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
categoryPNConnectedCategory
operationPNSubscribeOperation
affectedChannelsThe channels affected in the operation, of type array.
subscribedChannelsAll the current subscribed channels, of type array.
affectedChannelGroupsThe channel groups affected in the operation, of type array.
lastTimetokenThe last timetoken used in the subscribe request, of type long.
currentTimetokenThe current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
{
category: 'PNConnectedCategory',
operation: 'PNSubscribeOperation',
affectedChannels: ['my_channel_1'],
subscribedChannels: ['my_channel_1'],
affectedChannelGroups: [],
lastTimetoken: '14974492380756600',
currentTimetoken: '14974492384874375'
}
The following objects will be returned in the Subscribe Message Response
ObjectDescription
channelThe channel for which the message belongs.
subscriptionThe channel group or wildcard subscription match (if exists).
timetokenPublish timetoken.
messageThe payload.
actualChannelDeprecated. Use property channel.
subscribedChannelDeprecated. Use property subscription.
{
actualChannel: null,
channel: "my_channel_1",
message: "Hello World!",
publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
subscribedChannel: "my_channel_1",
subscription: null,
timetoken: "14966804541029440"
}
The following objects will be returned in the Presence Response
ObjectDescription
actionCan be join, leave, state-change or timeout.
channelThe channel for which the message belongs.
occupancyNo. of users connected with the channel.
stateUser State.
subscriptionThe channel group or wildcard subscription match (if exists)
timestampCurrent timetoken.
timetokenPublish timetoken.
uuidUUIDs of users who are connected with the channel.
{
category: 'PNConnectedCategory',
operation: 'PNSubscribeOperation',
affectedChannels: ['my_channel_1'],
subscribedChannels: ['my_channel_1'],
affectedChannelGroups: [],
lastTimetoken: '14974492380756600',
currentTimetoken: '14974492384874375'
}

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.

pubnub.subscribe({
channels: ['my_channel_1', 'my_channel_2', 'my_channel_3']
});
Subscribing to a Presence channel
Requires Presence add-on

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

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.

pubnub.subscribe({
channels: ["my_channel"],
withPresence: true,
});
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 (.).

pubnub.subscribe({
channels: ["ab.*"],
});
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 add-on

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

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.

const pubnub = new PubNub({
/* initiation arguments */
});

pubnub.addListener({
status: async (statusEvent) => {
if (statusEvent.category === "PNConnectedCategory") {
try {
await pubnub.setState({
state: {
some: "state",
},
});
} catch (status) {
// handle setState error
show all 29 lines
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.

pubnub.subscribe({
channelGroups: ["my_channelGroup"],
});
Subscribe to the presence channel of a channel group
note
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.

pubnub.subscribe({
channelGroups: ["family"],
withPresence: true,
});
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.

pubnub.subscribe({
channelGroups: ["my_channelGroup1", "my_channelGroup2", "my_channelGroup3"],
});
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.

pubnub.subscribe({
channels: ["my_channel"],
channelGroups: ["my_channelGroup"],
});
Sample Responses
Join Event
{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "join",
"timetoken": "15119466699655811",
"occupancy": 2,
"uuid": "User1",
"timestamp": 1511946669
}
Leave Event
{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "leave",
"timetoken": "15119446002445794",
"occupancy": 1,
"uuid": "User1",
"timestamp": 1511944600
}
Timeout Event
{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "timeout",
"timetoken": "15119519897494311",
"occupancy": 3,
"uuid": "User2",
"timestamp": 1511951989
}
Custom Presence Event (State Change)
{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "state-change",
"state": {
"isTyping": true
},
"timetoken": "15119477895378127",
"occupancy": 5,
"uuid": "User4",
"timestamp": 1511947789
}
Interval Event
{
"action": "interval",
"occupancy": 2,
"timestamp": 1511947739
}

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:

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

If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), 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.

{
"channel": "my_channel",
"subscription": null,
"actualChannel": null,
"subscribedChannel": "my_channel-pnpres",
"action": "interval",
"timetoken": "15119477396210903",
"occupancy": 4,
"timestamp": 1511947739,
"here_now_refresh" : true
}

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

Listeners should be added before calling the method.

Add Listeners

pubnub.addListener({
// Messages
message: function (m) {
const channelName = m.channel; // Channel on which the message was published
const channelGroup = m.subscription; // Channel group or wildcard subscription match (if exists)
const pubTT = m.timetoken; // Publish timetoken
const msg = m.message; // Message payload
const publisher = m.publisher; // Message publisher
},
// Presence
presence: function (p) {
const action = p.action; // Can be join, leave, state-change, or timeout
const channelName = p.channel; // Channel to which the message belongs
const occupancy = p.occupancy; // Number of users subscribed to the channel
const state = p.state; // User state
show all 71 lines

Remove Listeners

var existingListener = {
message: function () {
},
};

pubnub.removeListener(existingListener);
Listener status events
CategoryDescription
PNNetworkUpCategoryThe SDK detected that the network is online.
PNNetworkDownCategoryThe SDK announces this when a connection isn't available, or when the SDK isn't able to reach PubNub servers.
PNNetworkIssuesCategoryA 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.
PNReconnectedCategoryThe SDK was able to reconnect to PubNub.
PNConnectedCategorySDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes.
PNAccessDeniedCategoryAccess Manager permission failure.
PNMalformedResponseCategoryJSON parsing crashed.
PNBadRequestCategoryThe server responded with a bad response error because the request is malformed.
PNDecryptionErrorCategoryIf using decryption strategies and the decryption fails.
PNTimeoutCategoryFailure to establish a connection to PubNub due to a timeout.
PNRequestMessageCountExceedCategoryThe SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold.
PNUnknownCategoryReturned when the subscriber gets a non-200 HTTP response code from the server.

Unsubscribe (deprecated)

Deprecated

This method is deprecated. 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:

pubnub.unsubscribe({
channels: Array<string>,
channelGroups: Array<string>
}): Promise<UnsubscribeResponse>;
ParameterTypeRequiredDescription
Operation ArgumentsHashYesA hash of arguments.
channelsArray<string>YesSpecifies the channel to unsubscribe from.
channelGroupsArray<string>Specifying either channels or channelGroups is mandatorySpecifies the channelGroups to unsubscribe from.

Basic Usage

Unsubscribe from a channel:

pubnub.unsubscribe({
channels: ["my_channel"],
});

Response

The output below demonstrates the response to a successful call:

{
"action" : "leave"
}

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.

pubnub.unsubscribe({
channels: ["chan1", "chan2", "chan3"],
});
Example Response
{
"action" : "leave"
}
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.

pubnub.unsubscribe({
channelGroups: ["demo_group1", "demo_group2"],
});

Unsubscribe All (deprecated)

Deprecated

This method is deprecated. Use Unsubscribe all instead.

Unsubscribe from all channels and all channel groups

Method(s)

unsubscribeAll()

Basic Usage

pubnub.unsubscribeAll();

Returns

None

Last updated on