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 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.
|
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
Publish a message to a channel
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
Store the published message for 10 hours
Publish successful
Publish unsuccessful by network down
Publish unsuccessful by initialization without publishKey
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 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
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 |