The maximum message byte size that can be published in PubNub is 32,768 bytes 32 KiB. It is necessary to prevent yourself from getting a Message Too Large gateway response by ensuring you are not going to be sending message payloads that are too large. The best way to test this before sending is to use the following pattern for potential message payload size. 

Normally this is not necessary if you generally cap your message size well below 32 KiB, but if you want to approach the absolute limit, here is the solution.

Create a function in your application that can be called from wherever you publish a message in your application. You probably already have a "util" package with other types of helper functions. This function assumes the message is JSON, so be sure to adjust to your specific message format, as required.

function calculate_payload_size( channel, message ) {
    return encodeURIComponent(
        channel + JSON.stringify(message)
    ).length + 100;

Below is an example of calling the above function with a sample message that is obviously well under the limit.

var channel = "chats.room1";
var msg = {"msg":"Let's meet up after work."};
var size = calculate_payload_size(channel, message);
console.log("Payload Size: ", size);

if (size < 32768) {
    {channel: channel, message: msg},
    function(status, response) {console.log(status, response);}

NOTE: You will want to ensure UTF-8 message encoding before calculating the string length. On a mobile platform with keyboards that support multi-byte chars and unicode emoji, calculating payload size can be challenging.

See Also