Node.jsNode.jsPhoneGapReact V4WebJavaScriptNode.JS V4 Publish & Subscribe API Reference for Realtime Apps

Go to Configuration


The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
 
Publish Anytime
It is not required to be subscribed to a channel in order to publish to that channel.
Message Data:
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. Message data should not contain special NodeJS V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Message Size:
The maximum number of characters per message is 32K by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5KB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details please check: https://support.pubnub.com/support/discussions/topics/14000006322

Message Publish Rate:
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber cannot keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels.
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably.
There are some best practices to ensure messages are delivered when publishing to a channel:
  • Publish to any given channel in a serial manner (i.e. not concurrently).
  • Check that the return code is success (e.g. [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not Use JSON.stringify!
It is important to note that you should not use JSON.stringify() when sending signals/messages via PubNub. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the NodeJS V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    message ObjectYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
    channel String YesSpecifies channel name to publish messages to.
    storeInHistory Boolean Optionaltrue

    If true the messages are stored in history.

    If storeInHistory is not specified, then the history configuration on the key is used.

    sendByPost Boolean OptionalfalseIf true the messages sent via POST.
    meta Object OptionalPublish extra meta with the request.
    ttlNumberOptional
    Set a per message time to live in storage.
    1. If storeInHistory = true, and ttl = 0, the message is stored with no expiry time.
    2. If storeInHistory = true and ttl = X (X is an Integer value), the message is stored with an expiry time of X hours.
    3. If storeInHistory = false, the ttl parameter is ignored.
    4. If ttl is not specified, then expiration of the message defaults back to the expiry value for the key.
    callback FunctionOptionalExecutes on a successful/unsuccessful publish.

Publish a message to a channel:

pubnub.publish(
    {
        message: { 
            such: 'object' 
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: { 
            "cool": "meta"
        }   // publish extra meta with the request
    }, 
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status)
        } else {
            console.log("message Published w/ timetoken", response.timetoken)
        }
    }
);
 
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.
type PublishResponse = {
    timetoken: number
}
  1. var newMessage = {
        text: 'Hi There!'
    }
    pubnub.publish(
        {
            message: newMessage,
            channel: 'my_channel'
        }, 
        function(status, response) {
            if (status.error) {
                console.log("publishing failed w/ status: ", status);
            } else {
                console.log("message published w/ server response: ", response);
            }
        }
    );
  2. pubnub.publish(
        {
            message: 'hello!',
            channel: 'my_channel',
            storeInHistory: true,
            ttl: 10
        }, 
        function(status, response) {
            if (status.error) {
                console.log("publishing failed w/ status: ", status);
            } else {
                console.log("message published w/ server response: ", response);
            }
        }
    );
  3. pubnub.publish({
        message: { 
            such: 'object'
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        storeInHistory: false, //override default storage options
        meta: { 
            "cool": "meta"
        }   // publish extra meta with the request
    }).then((response) => {
        console.log(response)
    }).catch((error) => {
        console.log(error)
    });
  4. var newMessage = {
        text: 'Hi There!'
    }
    pubnub.publish({
        message: newMessage,
        channel: 'my_channel'
    }).then((response) => {
        console.log(response)
    }).catch((error) => {
        console.log(error)
    });
  5. pubnub.publish({
        message: 'hello!',
        channel: 'my_channel',
        storeInHistory: true,
        ttl: 10
    }).then((response) => {
        console.log(response)
    }).catch((error) => {
        console.log(error)
    });
The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the NodeJS V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    message ObjectYesThe message may be any valid JSON type including objects, arrays, strings, and numbers.
    channel String YesSpecifies channel name to publish messages to.
    sendByPost Boolean OptionalfalseIf true the messages sent via POST.
    meta Object OptionalPublish extra meta with the request.
    callback FunctionOptionalExecutes on a successful/unsuccessful publish.

Fire a message to a channel:

pubnub.fire(
    {
        message: { 
            such: 'object' 
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        meta: { 
            "cool": "meta"
        }   // fire extra meta with the request
    }, 
    function (status, response) {
        if (status.error) {
            // handle error
            console.log(status);
        } else {
            console.log("message published w/ timetoken", response.timetoken);
        }
    }
);
  1. pubnub.fire({
        message: { 
            such: 'object'
        },
        channel: 'my_channel',
        sendByPost: false, // true to send via post
        meta: { 
            "cool": "meta"
        }   // fire extra meta with the request
    }).then((response) => {
        console.log(response);
    }).catch((error) => {
        console.log(error);
    });
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribeKey at initialization.
By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.
 

You can be notified of connectivity via the listener, on establishing connection the statusEvent.category returns PNConnectedCategory.

By waiting for the connect event to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.

 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the NodeJS V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    channels ArrayYesSpecifies the channels to subscribe to. It is possible to specify multiple channels as a list or as an array.
    channelGroupsArraySpecifying either channels or channelGroups is mandatorySpecifies the channelGroups to subscribe to.
    withPresence Boolean OptionalfalseIf true it also subscribes to presence instances.
    timetoken Number OptionalSpecifies timetoken from which to start returning any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service.
Subscribe to a channel:
pubnub.subscribe({
    channels: ['my_channel'],
});
The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.
ObjectDescription
categoryPNConnectedCategory
operationPNSubscribeOperation
affectedChannelsThe channels affected in the operation, of type array.
subscribedChannelsAll the current subscribed channels, of type array.
affectedChannelGroupsThe channel groups affected in the operation, of type array.
lastTimetokenThe last timetoken used in the subscribe request, of type long.
currentTimetokenThe current timetoken fetched in the subscribe response, which is going to be used in the next request, of type long.
{
    category: 'PNConnectedCategory',
    operation: 'PNSubscribeOperation',
    affectedChannels: ['my_channel_1'],
    subscribedChannels: ['my_channel_1'],
    affectedChannelGroups: [],
    lastTimetoken: '14974492380756600',
    currentTimetoken: '14974492384874375'
}
ObjectDescription
channelThe channel for which the message belongs.
subscriptionThe channel group or wildcard subscription match (if exists).
timetokenPublish timetoken.
messageThe payload.
actualChannelDeprecated. Use property channel.
subscribedChannelDeprecated. Use property subscription.
{
    actualChannel: null,
    channel: "my_channel_1",
    message: "Hello World!",
    publisher: "pn-58e1a647-3e8a-4c7f-bfa4-e007ea4b2073",
    subscribedChannel: "my_channel_1",
    subscription: null,
    timetoken: "14966804541029440"
}
ObjectDescription
actionCan be join, leave, state-change or timeout.
channelThe channel for which the message belongs.
occupancyNo. of users connected with the channel.
stateUser State.
subscriptionThe channel group or wildcard subscription match (if exists)
timestampCurrent timetoken.
timetokenPublish timetoken.
uuidUUIDs of users who are connected with the channel.
{
    category: 'PNConnectedCategory',
    operation: 'PNSubscribeOperation',
    affectedChannels: ['my_channel_1'],
    subscribedChannels: ['my_channel_1'],
    affectedChannelGroups: [],
    lastTimetoken: '14974492380756600',
    currentTimetoken: '14974492384874375'
}
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    pubnub.subscribe({
        channels: ['my_channel_1', 'my_channel_2', 'my_channel_3']
    });
  2. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.
    pubnub.subscribe({
    	channels: ['my_channel'],
    	withPresence: true
    });
    
    {
        "channel": "my_channel",
        "subscription": null,
        "actualChannel": null,
        "subscribedChannel": "my_channel-pnpres",
        "action": "join",
        "timetoken": "15119466699655811",
        "occupancy": 2,
        "uuid": "User1",
        "timestamp": 1511946669
    }
    
    {
        "channel": "my_channel",
        "subscription": null,
        "actualChannel": null,
        "subscribedChannel": "my_channel-pnpres",
        "action": "leave",
        "timetoken": "15119446002445794",
        "occupancy": 1,
        "uuid": "User1",
        "timestamp": 1511944600
    }
    {
       "channel": "my_channel",
       "subscription": null,
       "actualChannel": null,
       "subscribedChannel": "my_channel-pnpres",
       "action": "timeout",
       "timetoken": "15119519897494311",
       "occupancy": 3,
       "uuid": "User2",
       "timestamp": 1511951989
    }
    {
        "channel": "my_channel",
        "subscription": null,
        "actualChannel": null,
        "subscribedChannel": "my_channel-pnpres",
        "action": "state-change",
        "state": {
            "isTyping": true
        },
        "timetoken": "15119477895378127",
        "occupancy": 5,
        "uuid": "User4",
        "timestamp": 1511947789
    }
    {
        "action": "interval",
        "occupancy": 2,
        "timestamp": 1511947739
    }

    When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

    • joined
    • left
    • timedout

    For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

    {
        "channel": "my_channel",
        "subscription": null,
        "actualChannel": null,
        "subscribedChannel": "my_channel-pnpres",
        "action": "interval",
        "timetoken": "15119477396210903",
        "occupancy": 4,
        "timestamp": 1511947739
    }

    If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

    {
        "channel": "my_channel",
        "subscription": null,
        "actualChannel": null,
        "subscribedChannel": "my_channel-pnpres",
        "action": "interval",
        "timetoken": "15119477396210903",
        "occupancy": 4,
        "timestamp": 1511947739,
        "here_now_refresh" : true
    }
  3. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).
     
    3 levels (2 dots) of wildcarding is supported, e.g.:
    a.*
    a.b.*
    pubnub.subscribe({
        channels: ['ab.*'] 
    });
  4. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    You can set state for a uuid during a subscribe by using the state parameter. Simply specify the desired key/value pairs as a JSON object.
    var pubnub = new PubNub({ 
    	/* initiation arguments */ 
    })
    pubnub.addListener({
    	status: function(statusEvent) {
    		if (statusEvent.category === "PNConnectedCategory") {
    			var newState = {
    				new: 'state' 
    			};
    			pubnub.setState(
    				{ 
    					state: newState 
    				}, 
    				function (status) {
    					// handle state setting response
    				}
    			);
    		}
    	},
    	message: function(message) {
    		// handle message
    	},
    	presence: function(presenceEvent) {
    		// handle presence
    	}
    })
    
    pubnub.subscribe({ 
    	channels: ['ch1', 'ch2', 'ch3'] 
    });
  5. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe({
    	channelGroups: ['my_channelGroup']
    });
  6. Requires Stream Controller and Presence add-on XRequires that both Stream Controller and Presence add-ons are enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe({
        channelGroups: ['family'],
        withPresence: true
    });
  7. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe({
        channelGroups: ['my_channelGroup1', 'my_channelGroup2', 'my_channelGroup3']
    });
  8. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe({
        channels: ['my_channel'],
        channelGroups: ['my_channelGroup']
    });
When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Unsubscribe from a channel you can use the following method(s) in the NodeJS V4 SDK:
  1. ParameterTypeRequiredDescription
    Operation ArgumentsHashYesA hash of arguments.
    channelsArray YesSpecifies the channel to unsubscribe from.
    channelGroups ArraySpecifying either channels or channelGroups is mandatorySpecifies the channelGroups to unsubscribe from.
Unsubscribe from a channel:
pubnub.unsubscribe({
    channels: ['my_channel']
})
The output below demonstrates the response to a successful call:
{
	"action" : "leave"
}
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.unsubscribe({
    	channels: ['chan1', 'chan2', 'chan3']
    })
    
    {
    	"action" : "leave"
    }
    
  2. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.unsubscribe({
        channelGroups : ['demo_group1', 'demo_group2']
    });
Unsubscribe from all channels and all channel groups
  • unsubscribeAll()
pubnub.unsubscribeAll();
None

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

pubnub.addListener({
    message: function(m) {
        // handle message
        var channelName = m.channel; // The channel for which the message belongs
        var channelGroup = m.subscription; // The channel group or wildcard subscription match (if exists)
        var pubTT = m.timetoken; // Publish timetoken
        var msg = m.message; // The Payload
        var publisher = m.publisher; //The Publisher
    },
    presence: function(p) {
        // handle presence
        var action = p.action; // Can be join, leave, state-change or timeout
        var channelName = p.channel; // The channel for which the message belongs
        var occupancy = p.occupancy; // No. of users connected with the channel
        var state = p.state; // User State
        var channelGroup = p.subscription; //  The channel group or wildcard subscription match (if exists)
        var publishTime = p.timestamp; // Publish timetoken
        var timetoken = p.timetoken;  // Current timetoken
        var uuid = p.uuid; // UUIDs of users who are connected with the channel
    },
    status: function(s) {
        var affectedChannelGroups = s.affectedChannelGroups;
        var affectedChannels = s.affectedChannels;
        var category = s.category;
        var operation = s.operation;
    }
});
var existingListener = {
    message: function() {
    } 
}

pubnub.removeListener(existingListener)
CategoriesDescription
PNNetworkUpCategory
SDK detected that network is online.
PNNetworkDownCategory
SDK detected that network is down.
PNNetworkIssuesCategory
A subscribe event experienced an exception when running.
PNReconnectedCategory
SDK was able to reconnect to pubnub.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAccessDeniedCategory
PAM permission failure.
PNMalformedResponseCategory
JSON parsing crashed.
PNBadRequestCategory
Server rejected the request.
PNDecryptionErrorCategory
If using decryption strategies and the decryption fails.
PNTimeoutCategory
Failure to establish connection due to timeout.

Go to Presence