Send messages

Sending messages is the cornerstone of PubNub. We guarantee that any message you send will be delivered anywhere in the world in under 100ms. This means your messages are literally sent 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 sending a message successfully, PubNub servers will send a response including a timetoken, which is an exact timestamp (17 digit value to the nearest 10th nanosecond) of when the message was published. Timetokens are useful if you want to work with historical messages, but we'll talk about this later on.

Depending on your needs, you can structure your payload in different ways, 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 what you want to send, you always send it to a channel.

You can think of a channel as a tunnel through which PubNub transmits data from one device to another. When you're sending a message, you must specify a channel to send the message to. You may only send a message to one channel at a time.

In the code below, the message is sent to the channel with the ID of my_channel.

pubnub.publish(
{
channel: "my_channel",
message: {"text": "This is my first realtime 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