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 30ms. 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
publish()
sends a message to all channel subscribers. A successfully published message is replicated across PubNub's points of presence and sent simultaneously to all subscribed clients on a channel.
- Prerequisites and limitations
- Security
- Message data
- Size
- Publish rate
- Custom message type
- Best practices
- 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.
You can secure the messages with SSL/TLS by setting ssl
to true
during initialization. You can also encrypt messages.
The message can contain any JSON-serializable data (Objects, Arrays, Ints, Strings) and shouldn't contain any special classes or functions. String content can include any single-byte or multi-byte UTF-8 characters.
Don't JSON serialize
You should not JSON serialize the message
and meta
parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB, including the final escaped character count and the channel name. An optimal message size is under 1800 bytes.
If the message you publish exceeds the configured size, you receive a Message Too Large
error. If you want to learn more or calculate your payload size, refer to Message Size Limit.
You can publish as fast as bandwidth conditions 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, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
You can optionally provide the customMessageType
parameter to add your business-specific label or category to the message, for example text
, action
, or poll
.
- 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 according to your app's latency needs, for example no more than 5 messages per second.
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,
customMessageType: string
}): Promise<PublishResponse>;
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
message | any | Yes | The message may be any valid JSON type including objects, arrays, strings, and numbers. | |
channel | string | Yes | Specifies channel name to publish messages to. | |
storeInHistory | boolean | Optional | true | If true the messages are stored in history. If storeInHistory is not specified, then the history configuration on the key is used. |
sendByPost | boolean | Optional | 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 | any | Optional | Publish extra meta with the request. | |
ttl | number | Optional | Set a per message time to live in Message Persistence.
| |
customMessageType | string | Optional | 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 . |
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
customMessageType: "text-message",
});
} catch (status) {
console.log(status);
show all 16 linesSubscribe 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",
customMessageType: "text-message",
});
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,
customMessageType: "text-message",
});
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
})
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
message | Object | Yes | The message may be any valid JSON type including objects, arrays, strings, and numbers. | |
channel | String | Yes | Specifies channel name to publish messages to. | |
sendByPost | Boolean | Optional | false | If true the messages sent via POST. |
meta | Object | Optional | Publish 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 linesOther 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,
customMessageType: string,
}): Promise<SignalResponse>;
Parameter | Type | Required | Description |
---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. |
message | string | Yes | The message may be any valid JSON type including objects, arrays, strings, and numbers. |
channel | string | Yes | Specifies channel name to send messages to. |
customMessageType | string | Optional | 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 . |
Basic Usage
Signal a message to a channel
const result = await pubnub.signal({
message: "hello",
channel: "foo",
customMessageType: "text-message",
});
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 singlepubnub
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 subscription
s 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)
Parameter | Type | Required | Description |
---|---|---|---|
subscriptionOptions | subscriptionOptions | No | Subscription 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
}))
Parameter | Type | Required | Description |
---|---|---|---|
→ channels | string[] | No | Channels to subscribe to. Either channels or channelGroups is mandatory. |
→ channelGroups | string[] | No | Channel groups to subscribe to. Either channels or channelGroups is mandatory. |
→ subscriptionOptions | subscriptionOptions | No | Subscription 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:
Option | Type | Description |
---|---|---|
receivePresenceEvents | boolean | Whether presence updates for userId should be delivered through the listener streams. For more 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. |
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 linesCreate 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)
Parameter | Type | Required | Description |
---|---|---|---|
channel | string | Yes | The 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)
Parameter | Type | Required | Description |
---|---|---|---|
channel_group | string | Yes | The 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)
Parameter | Type | Required | Description |
---|---|---|---|
channelMetadata | string | Yes | The 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)
Parameter | Type | Required | Description |
---|---|---|---|
userMetadata | string | Yes | The 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 Reaction event: ", messageActionEvent); };
subscription.onFile = (fileEvent) => { console.log("File event: ", fileEvent); };
// Generic listeners
show all 77 linesBasic 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 linesAdd 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>;
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
Operation Arguments | Hash | Yes | A hash of arguments. | |
channels | Array<string> | Yes | Specifies the channels to subscribe to. It is possible to specify multiple channels as a list or as an array. | |
channelGroups | Array<string> | Specifying either channels or channelGroups is mandatory | Specifies the channelGroups to subscribe to. | |
withPresence | boolean | Optional | false | If true it also subscribes to presence instances. |
timetoken | number | Optional | 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. |