Publish/Subscribe API for JavaScript SDK
PubNub delivers messages worldwide in less than 30 ms. 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.
- 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.
Secure messages with Transport Layer Security (TLS) or Secure Sockets Layer (SSL) by setting ssl
to true
during initialization. You can also encrypt messages.
The message can contain any JavaScript Object Notation (JSON)-serializable data (objects, arrays, integers, strings). Avoid special classes or functions. Strings can include any 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. This includes the escaped character count and the channel name. Aim for under 1,800 bytes for optimal performance.
If your message exceeds the limit, you'll receive a Message Too Large
error. To learn more or calculate payload size, see Message size limits.
You can publish as fast as bandwidth allows. There is a soft throughput limit because messages may drop if subscribers can't keep up.
For example, publishing 200 messages at once may cause the first 100 to drop if a subscriber hasn't received any yet. The in-memory queue stores only 100 messages.
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 a channel serially (not concurrently).
- Verify a success return code (for example,
[1,"Sent","136074940..."]
). - Publish the next message only after a success return code.
- On failure (
[0,"blah","<timetoken>"]
), retry. - Keep the in-memory queue under 100 messages to avoid drops.
- Throttle bursts to meet 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:
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>;
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
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