Publish/Subscribe API for 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 | Description |
---|---|
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 channel name 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.
|
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 . |
Basic Usage
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
const PubNub = require('pubnub');
// Initialize PubNub with demo keys
const pubnub = new PubNub({
publishKey: 'demo',
subscribeKey: 'demo',
userId: 'myUniqueUserId'
});
// Function to publish a message
async function publishMessage() {
try {
const result = await pubnub.publish({
message: { text: "Hello World" },
channel: "my_channel",
show all 28 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 | Description |
---|---|
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 name 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. |
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 | Description |
---|---|
message *Type: string | The message may be any valid JSON type including objects, arrays, strings, and numbers. |
channel *Type: string | Specifies channel name 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 . |
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.
Conceptual overview
For more general information about subscriptions, refer to Subscriptions.
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 | Description |
---|---|
subscriptionOptions Type: subscriptionOptions | 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 | Description |
---|---|
→ 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. |
Add/remove sets
You can add and remove subscription sets to create new sets. Refer to the Other examples section for more information.