Send messages

Sending messages is the cornerstone of PubNub. We guarantee that any message you send is delivered worldwide in under 30 ms. Messages arrive in the blink of an eye.

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.

{
"content": {
"type": "text",
"message": "This is a message!"
},
"sender": "Thomas Anderson"
}

After you publish a message, PubNub returns a response that includes a timetoken, an exact timestamp (17‑digit value to the nearest 10th nanosecond) of when the message was published. Timetokens help you work with historical messages.

Depending on your needs, you can change the structure and add a custom type to your messages, send small bits of data designed for high volumes, or even send a file. If you need an extra layer of security, you might want to consider encrypting your messages and files.

Regardless of the payload, you always send it to a channel.

Think of a channel as a tunnel that PubNub uses to transmit data between devices. When you send a message, you must specify the channel. You can send a message to one channel at a time.

In the code below, the message of the text-message custom type is sent to the channel with the ID of my_channel. Note that not all SDKs yet support sending messages with a custom message type.

pubnub.publish(
{
channel: "my_channel",
message: {"text": "This is my first realtime message!"},
customMessageType: "text-message"
},
function(status, response) {
console.log(status);
console.log(response);
}
);

You don't need to create a channel before you send a message to it. A channel is created automatically when the first message is sent. All you need to do is provide the channel name. Try to be as descriptive as possible and adopt our channel naming convention in order not to miss out on certain PubNub features.

When you've sent your first message, you can check if it's been correctly sent by using the PubNub Debug Console, but now it's only natural to wonder how to receive messages someone else sent. Let's look into that.

Last updated on
On this page