Publish/Subscribe API for JavaScript SDK
PubNub's publish-processing latency, the time to accept and acknowledge a publish request, is about 0.5 ms within the same region. 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.
Need larger messages?
PubNub supports payloads larger than the standard limit, but raising it requires verifying compatibility with your use case.
Talk to our team to discuss increasing the message size limit for your use case.
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. |
storeInHistoryType: 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. |
sendByPostType: 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. |
metaType: any Default: n/a | Publish extra meta with the request. |
ttlType: number Default: n/a | Set a per message time to live in Message Persistence.
|
customMessageTypeType: 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
Publish successful
1
Publish unsuccessful by network down
1
Publish unsuccessful by initialization without a publish key
1
Fire
The fire endpoint sends a message to Functions event handlers and Illuminate. The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via fire() aren't replicated to subscribers and aren't stored in history.
Method(s)
To Fire a message, you can use the following method(s) in the JavaScript SDK:
1fire({
2 Object message,
3 String channel,
4 Boolean sendByPost,
5 Object meta
6})
| 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. |
sendByPostType: Boolean Default: false | If true the messages sent via POST. |
metaType: Object Default: n/a | Publish extra meta with the request. |
Sample code
Fire a message to a channel
1
Signal
The signal() function sends 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:
1pubnub.signal({
2 message: string,
3 channel: string,
4 customMessageType: string,
5}): 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 ID to send messages to. |
customMessageTypeType: 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. |
Sample code
Signal a message to a channel
1
Response
1type SignalResponse = {
2 timetoken: number
3}
Subscribe
The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified SDK entity or set of SDK entities. To subscribe successfully, configure the appropriate subscribeKey at initialization.
Conceptual overview
For more general information about subscriptions, refer to Subscriptions.
SDK 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 SDK 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.
Subscribe only opens the connection
Calling subscribe() opens a connection but doesn't deliver messages to your code. You must also add event listeners to receive messages and access sender information. The message object received through listeners includes the sender's ID in the publisher field.
Subscription scope
Subscriptions let you attach listeners for specific real-time update types. Your app receives messages and events through those listeners. There are two types:
subscription: created from an SDK entity and scoped to that entity (for example, a particular channel)subscriptionSet: created from the PubNub client and scoped to the client (for example, all subscriptions created on a singlepubnubobject). A set can include one or more subscriptions.
The event listener is a single point through which your app receives all the messages, signals, and events in the SDK entities you subscribed to. For information on adding event listeners, refer to Event listeners.
Add subscriptions to an existing set
If you subscribe to a subscription set and then add more subscriptions to it, they are automatically subscribed to.
Create a subscription
An entity-level subscription allows you to receive messages and events for only that SDK entity for which it was created. Using multiple entity-level subscriptions is useful for handling various message/event types differently in each channel.
1// SDK entity-based, local-scoped
2const channel = pubnub.channel('channel_1');
3channel.subscription(subscriptionOptions)
| Parameter | Description |
|---|---|
subscriptionOptionsType: subscriptionOptions | Subscription behavior configuration. |
Create a subscription set
A client-level subscriptionSet allows you to receive messages and events for all SDK entities in the set. A single subscriptionSet is useful for similarly handling various message/event types in each channel.
1// client-based, general-scoped
2pubnub.subscriptionSet({
3 channels: string[],
4 channelGroups: string[],
5 subscriptionOptions: subscriptionOptions
6}))
| Parameter | Description |
|---|---|
> channelsType: string[] | Channels to subscribe to. Either channels or channelGroups is mandatory. |
> channelGroupsType: string[] | Channel groups to subscribe to. Either channels or channelGroups is mandatory. |
> subscriptionOptionsType: subscriptionOptions | Subscription behavior configuration. |
subscriptionOptions
subscriptionOptions is a class. Available properties include:
| Option | Type | Description |
|---|---|---|
receivePresenceEvents | boolean | Whether presence updates for userIds should be delivered through the listener streams. For 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. |
Modify a subscription set
You can add and remove subscriptions to and from an existing set to create new sets. If you subscribe to a subscription set and then add more subscriptions to it, they are automatically subscribed to.
Refer to the Other examples section for more information on adding and removing subscriptions.
Method(s)
subscription and subscriptionSet use the same subscribe() method.
Subscribe
To subscribe, you can use the following method in the JavaScript SDK:
1subscription.subscribe()
2subscriptionSet.subscribe()
Sample code
- JavaScript
- React
1
In React, create the subscription inside a useEffect hook and unsubscribe in the cleanup function to avoid memory leaks when the component unmounts.
1import React, { useEffect } from 'react';
2import PubNub from 'pubnub';
3
4const pubnub = new PubNub({
5 publishKey: 'YOUR_PUBLISH_KEY',
6 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
7 userId: 'YOUR_USER_ID',
8});
9
10function SubscribedComponent() {
11 useEffect(() => {
12 const channel = pubnub.channel('my_channel');
13 const subscription = channel.subscription({
14 receivePresenceEvents: true,
15 });
show all 24 linesWildcard subscribe and message objects
Wildcard subscribe (e.g., sports.*) works the same as regular subscribe - you still need to add event listeners to receive messages. The message objects received include the sender's ID in the publisher field, the actual channel name in the channel field, and the wildcard match in the subscription field.
Other examples
Create a subscription set from 2 individual subscriptions
1
Create a subscription set from 2 sets
1
Add subscriptions to an existing set
1
Returns
The subscribe() method doesn't have a return value.
SDK entities
SDK entities (also called entity handles) are subscribable objects for which you can receive real-time updates (messages, events, etc). An SDK entity is a local client-side handle: creating one performs no network call and does not require a matching server-side record to exist.
channelchannelGroupuserMetadatachannelMetadatadataSyncUser,dataSyncChannel,dataSyncEntity,dataSyncRelationship, anddataSyncMembership
SDK entity is not the same as a DataSync entity
An SDK entity is the local handle described in this section. A DataSync entity is a stored server-side record, the source of truth for your application state, managed through the DataSync API. The DataSync SDK entities below are SDK entities that subscribe to DataSync entities.
Create channels
This method returns a local channel SDK entity.
1pubnub.channel(string)
| Parameter | Description |
|---|---|
channel *Type: string | The ID of the channel to create a subscription of. |
Sample code
1
Create channel groups
This method returns a local channelGroup SDK entity.
1pubnub.channelGroup(string)
| Parameter | Description |
|---|---|
channel_group *Type: string | The name of the channel group to create a subscription of. |
Sample code
1
Create channel metadata
This method returns a local channelMetadata SDK entity.
1pubnub.channelMetadata(string)
| Parameter | Description |
|---|---|
channelMetadata *Type: string | The String identifier of the channel metadata object to create a subscription of. |
Sample code
1
Create user metadata
This method returns a local userMetadata SDK entity.
1pubnub.userMetadata(string)
| Parameter | Description |
|---|---|
userMetadata *Type: string | The String identifier of the user metadata object to create a subscription of. |
Sample code
1
DataSync SDK entities
These methods return local SDK entities that subscribe to the real-time updates of a DataSync object. They are the subscribe-side counterpart to the pubnub.dataSync.* read and write methods, and subscribe is the only API they expose.
| Method | Observes changes to |
|---|---|
pubnub.dataSyncUser(id) | A DataSync user |
pubnub.dataSyncChannel(id) | A DataSync channel |
pubnub.dataSyncEntity(id) | A DataSync entity |
pubnub.dataSyncRelationship(id) | A DataSync relationship |
pubnub.dataSyncMembership(id) | A DataSync membership |
| Parameter | Description |
|---|---|
id *Type: string | The identifier of the DataSync object to create a subscription of. Used verbatim, so a wildcard identifier such as product.* works as written. |
Relationship and membership changes are not delivered on their own id
A relationship change is delivered on the data channels of the two entities it links (entityAId and entityBId), and a membership change on those of its userId and channelId. It is never published on a channel named after the relationship or membership id, so dataSyncRelationship(id) and dataSyncMembership(id) receive nothing for the link itself. To watch memberships appear and disappear, observe the linked user and channel with dataSyncUser and dataSyncChannel instead. Refer to Where each event is delivered.
Method(s)
1pubnub.dataSyncEntity(id: string)
2 .subscription({ projection: string, receivePresenceEvents: boolean, cursor: object, filter: function })
DataSync SDK entities accept every subscriptionOptions property plus one of their own:
| Option | Type | Description |
|---|---|---|
projection | string | Name of the DataSync projection to observe. Omit it, or pass default or __default__, to observe the object itself. Any other name observes the projection on its own __{projection}__{id} channel. |
receivePresenceEvents is ignored, because a DataSync object is observed on a single data channel and has no presence channel.
The projection is chosen per subscription rather than per entity, so one entity can serve several projections at once. Each (id, projection) pair is subscribed and unsubscribed independently:
1const user = pubnub.dataSyncUser('user-alice')
2
3const base = user.subscription() // observes `user-alice`
4const admin = user.subscription({ projection: 'admin' }) // observes `__admin__user-alice`
Both subscriptions receive their own copy of a change, and the projected one carries whatever extra fields the admin projection exposes. Unsubscribing one leaves the other subscribed.
Identifiers are never rewritten
The identifier is passed through exactly as given. dataSyncUser('__admin__u1').subscription({ projection: 'admin' }) therefore observes __admin____admin__u1, and the SDK does not collapse the repeated prefix.
Sample code
Reference code
1
Other examples
Observe every entity whose id matches a pattern
Because the identifier is used verbatim, a wildcard identifier subscribes to the matching channel pattern and one subscription serves the whole set. event.channel reports the concrete delivery channel, while event.subscription reports the pattern that matched it. For a fanned-out event, the changed object's id can differ from the delivery channel, so identify it through event.message.data.id.
1
Combine DataSync subscriptions with other subscriptions
A DataSync subscription is an ordinary subscription, so it composes into a set with any other subscription.
1
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.
No built-in event throttling
The PubNub SDK delivers every incoming event to your listener as it arrives — there is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.
To reduce the number of messages delivered to your client in the first place, use Subscribe Filters to filter messages server-side before they reach your listener.
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)
1