Message Publish

The foundation of all our PubNub offerings is the ability to send a message that will be delivered anywhere in less than 30 ms. Below, we walk you through different ways to send a message.

icon

Need help. Flat tire. Kansas City.


A PubNub Message can contain any kind of serializable data, like objects, numbers and UTF-8 encoded strings. Its format may be plain text, a URL-encoded object, or most commonly, JavaScript Object Notation (JSON). The max size of a message is 32 Kibibytes (KiB). You can check the size of your message payload using our message size calculator.

Receiving messages

Add a listener to receive and handle incoming messages, signals, and events. If you're new to PubNub, review how to set up your account.

Send messages

The primary means for sending messages is using the Publish API. You may only send a message to one channel at a time. If you want to publish to multiple channels, you must create a channel group.

PubNub's network reliably supports unlimited publishes without waiting for response on the same TCP socket connection.

pubnub.publish(
{
channel: "my_channel",
message: {"text": "Hello World!"}
},
function(status, response) {
console.log(status);
console.log(response);
}
);

When you publish a message to a channel, you're asking PubNub Platform to deliver that message to everyone who is subscribed to that channel.

A PubNub message may be sent as plain text, URL-encoded object, and most commonly, JSON. For more information, refer to message types.

As you can see, in the above publish method we specify the channel on which to send the message, the message content we want to send and a way to capture the server response, which in most languages is an asynchronous callback. A successful response looks like this:

[1,"Sent","14375189629170609"]

The response has three parts:

  1. success flag: 1 = success, 0 = failed
  2. response message: Sent or Failed
  3. publish timetoken: exact timestamp of the message which is a 17 digit value to the nearest 10th nanosecond (can be converted to UNIX epoch by dividing by 10000).

The publish timetoken can be used later to retrieve (or augment) that message using Message Persistence.

HTTP streaming and pipelining

For details on streaming and pipelining, see this gist.

Send announcements to all users

You can send announcements to all users, or a limited set of users, in your application by using a channel to which the announcer has read/write access, and to which all other users have read-only access.

Once you have the channel set up, you can display any messages sent on the channel as announcements. Users with read access can subscribe to the channel to receive announcements, but can't send messages on the same channel.

pubnub.publish({
message: {
type: 'announcement',
text: 'Hello, this is an announcement'
},
channel: 'ch-1',
}, (status, response) => {
// handle status, response
});

Message specifications

The message property can contain any JSON serializable data (JSON isn't required, just recommended and is typical in most use cases), including: Objects, Arrays, Integers and Strings. String content can include any single-byte or multi-byte UTF-8 character.

JSON serialization

You don’t need to serialize a JSON object when sending messages. PubNub SDKs handle serialization.

Delivery

  • PubNub provides status and timing details for each publish.
  • The Sent status confirms that the PubNub Network received the message and forwarded it to connected subscribers.
  • Network conditions on the last mile can affect delivery outside PubNub’s control.

Subscribers with interrupted or offline connections can still retrieve missed messages. For status codes and retrieving missed and historical messages, see Connection Management and Message Persistence.

Order

As long as the publisher sends messages slower than the consumer can receive them, messages are typically kept in order.

If your app requires strict ordering, add a sequence field to the message payload and order by it.

Message size limit

The maximum number of characters per message is 32 KiB. The maximum message size is based on the final escaped character count, including the channel name.

If the message you publish exceeds the configured size, you'll receive the following message:

["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

If you expect your messages will be pushing the size limit, check the size of your message in our payload size calculator.

Payload Size: 0.00 KiB (0 bytes)

For more information on calculating payload size within your application, refer to our knowledge base.

Receive messages

To receive a message, your client should implement a message listener and subscribe to a channel in which the message is being published.

Send signals

Signals are ideal for high-volume, low-cost use cases. They're intended for sending small bits of data where the last sent data is the only important piece of information. For example, chat typing indicators, live GPS location updates, and sensor updates from IoT devices.

icon

Sounds like a solution: How we used PubNub to jazz up in-store audio experiences

Messages vs signals

Signals are similar to regular messages, with the following exceptions:

FeatureSignalsMessages
Payload size
Limited to 64 bytes (64B)
Up to 32 kilobytes (32KB)
Cost efficiency
Cost less than standard messages
Generally more expensive than signals
Persistence
Cannot be saved in Message Persistence (past signals cannot be accessed)
Can be saved and accessed through Message Persistence
Push Notifications
Cannot trigger Mobile Push Notifications
Can trigger Mobile Push Notifications
Use case suitability
Best for non-critical data streams, like geolocation updates
Suitable for critical and non-critical use cases
Metadata support
Do not support metadata
Support metadata
Channel separation

Signals and messages should be sent on separate channels to improve connection recovery behaviour.

Sending a signal is similar to publishing a message:

let gps = ["35.9296","-78.9482"];

pubnub.signal(
{
channel: "locations.route1",
message: gps
},
function(status, response) {
console.log(status, response);
}
);

The Signal response may not be as important to your application and could be omitted, but is dependent on your use case.

Receive signals

To receive a signal, your client should implement a signal listener and subscribe to a channel in which the signal is being sent.

Publish with metadata fields

The meta parameter allows you to attach additional data to messages that remains separate from the message payload. Metadata fields serve two important purposes in PubNub applications: enabling subscribe filtering and maintaining data accessibility when using message encryption.

Subscribe filtering

Metadata fields can be filtered using subscribe filters, enabling server-side message routing based on user roles, priorities, geographic location, or other criteria.

Key benefits of metadata fields include:

  • Subscribe filtering support - Metadata fields can be filtered using subscribe filters, enabling sophisticated message routing based on user roles, priorities, geographic location, or other criteria
  • Encryption compatibility - When using AES-256 or other message encryption, metadata fields remain unencrypted and accessible to PubNub services like Functions, Illuminate, and Subscribe Filtering, while the message payload stays encrypted

To include metadata with your published messages, prepare the metadata object and pass it via the meta parameter.

User ID / UUID

User ID is also referred to as UUID/uuid in some APIs and server responses but holds the value of the userId parameter you set during initialization.

// Publishing with comprehensive metadata
pubnub.publish(
{
channel: "notifications",
message: {
title: "System Maintenance",
body: "Scheduled maintenance window starting soon",
timestamp: new Date().toISOString()
},
meta: {
priority: "high",
department: "engineering",
region: "San Francisco",
publisher: pubnub.getUserId(),
requiresAck: true
show all 21 lines

In the above examples, the metadata enables powerful filtering capabilities on the subscriber side. For instance, subscribers could filter for:

  • High-priority messages: meta.priority == "high"
  • Department-specific notifications: meta.department == "engineering"
  • Regional content: meta.region == "San Francisco"
  • Messages requiring acknowledgment: meta.requiresAck == "true"

The metadata fields remain accessible even when message encryption is enabled, making them ideal for routing and filtering while keeping sensitive message content secure.

For complete subscribe filtering documentation and syntax reference, see Subscribe Filter Details.

Last updated on