Node.jsNode.jsPhoneGapReact V4WebJavaScriptNode.JS V4 Configuration API Reference for Realtime Apps

NodeJS V4 complete API reference for building Realtime Applications on PubNub, including basic usage and sample code

You must include the PubNub JavaScript SDK in your code before initializing the client.

var PubNub = require('pubnub')
This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publishKey and subscribeKey.
To Initialize Pubnub you can use the following method(s) in the NodeJS V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    Operation Arguments Hash YesA hash of arguments.
    subscribeKey StringYesSpecifies the subscribeKey to be used for subscribing to a channel. This key can be specified at initialization or along with a subscribe().
    publishKey String OptionalSpecifies the publishKey to be used for publishing messages to a channel. This key can be specified at initialization or along with a publish().
    secretKey String OptionalUsed for PAM operations (server only!!).
    cipherKey String OptionalIf passed, will encrypt the payloads.
    authKey StringOptionalIf PAM enabled, this key will be used on all requests.
    logVerbosity Boolean Optionalfalselog HTTP information.
    uuid String OptionalSDK generated random uuidUUID to use, if not passed, a random will be generated.
    ssl Boolean Optional falseIf set to true, requests will be made over HTTPS, by default it is false unless the script is running on an https page.
    origin String Optionalpubsub.pubnub.comIf a custom domain is required, SDK accepts it here.
    presenceTimeout Number Optional300

    How long the server will consider the client alive for presence.


    The value is in seconds.

    heartbeatInterval Number OptionalNot Set

    How often the client will announce itself to server.


    The value is in seconds.

    restore Boolean Optionalfalsetrue to allow catch up on the front-end applications.
    keepAliveBooleanOptional

    true for v4.18.0 onwards,

    false before v4.18.0

    If set to true, SDK will use the same TCP connection for each HTTP request, instead of opening a new one for each new request.
    keepAliveSettingsObjectOptional

    keepAliveMsecs: 1000


    freeSocketKeepAliveTimeout: 15000


    timeout: 30000


    maxSockets: Infinity


    maxFreeSockets: 256

    Set a custom parameters for setting your connection keepAlive if this is set to true.


    keepAliveMsecs: (Number) how often to send TCP KeepAlive packets over sockets.


    freeSocketKeepAliveTimeout: (Number) sets the free socket to timeout after freeSocketKeepAliveTimeout milliseconds of inactivity on the free socket.


    timeout: (Number) sets the working socket to timeout after timeout milliseconds of inactivity on the working socket.


    maxSockets: (Number) maximum number of sockets to allow per host.


    maxFreeSockets: (Number) maximum number of sockets to leave open in a free state.

    useInstanceId Boolean Optional InstanceId is created for each new instance done and this is a composition of the prefix pn- and an uuid v4, this instanceId is used for signing each request to the service.
    suppressLeaveEvents Boolean OptionalWhen true the SDK doesn't send out the leave requests.
    proxyProxyOptional

    Instruct the SDK to use a proxy configuration when communicating with PubNub servers.

    Supported Protocols are http, https, socks5, socks4 and pac.

    requestMessageCountThresholdNumberOptional

    PNRequestMessageCountExceededCategory is thrown when the number of messages into the payload is above of requestMessageCountThreshold.

    autoNetworkDetectionBooleanOptionalfalseWhen the network comes back, the SDK sends PNNetworkUpCategory.
    listenToBrowserNetworkEventsBooleanOptionaltrueIf the browser fails to detect the network changes from WiFi to LAN and vice versa or you get reconnection issues, set the flag to false. This also the SDK reconnection logic to take over.
// PubNub = require('pubnub'); 		ES5
import PubNub from 'pubnub';		ES6

var pubnub = new PubNub({
	subscribeKey: "mySubscribeKey",
	publishKey: "myPublishKey",
	secretKey: "secretKey",
	cipherKey: "myCipherKey",
	authKey: "myAuthKey",
	logVerbosity: true,
	uuid: "myUniqueUUID",
	ssl: true,
	presenceTimeout: 130
})
It returns the Pubnub instance for invoking PubNub APIs like publish(), subscribe(), history(), hereNow(), etc.
  1. // PubNub = require('pubnub'); 		ES5
    import PubNub from 'pubnub';		ES6
    
    var pubnub = new PubNub({
    	subscribeKey: "mySubscribeKey",
    	publishKey: "myPublishKey",
    	secretKey: "secretKey",
    	ssl: true
    })
  2. In the case where a client will only read messages and never publish to a channel, you can simply omit the publishKey when initializing the client:
    // Initialize for Read Only Client
     
    var pubnub = new PubNub({
        subscribeKey : 'demo'
    });
  3. Under certain circumstances it useful to use a custom UUID to help in identifying your users.
    var pubnub = new PubNub ({
        subscribeKey: "mySubscribeKey",
        uuid: "myUniqueUUID"
    })
    
  4. This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with ssl set to true. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

    // PubNub = require('pubnub'); 		ES5
    import PubNub from 'pubnub';		ES6
    
    var pubnub = new PubNub({
    	subscribeKey: "mySubscribeKey",
    	publishKey: "myPublishKey",
    	secretKey: "secretKey",
    	cipherKey: "myCipherKey",
    	authKey: "myAuthKey",
    	logVerbosity: true,
    	uuid: "myUniqueUUID",
    	ssl: true,
    	presenceTimeout: 130
    })
  5. Requires Access Manager add-on XRequires that the Access Manager 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.
     

    Anyone with the secretKey can grant and revoke permissions to your app. Never let your secretKey be discovered, and to only exchange it / deliver it securely. Only use the secretKey on secure environments such as node.js application or other server-side platforms.

    When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

    For applications that will administer PAM permissions, the API is initialized with the secretKey as in the following example:
    var pubnub = new PubNub({
        subscribeKey: "mySubscribeKey",
        publishKey: "myPublishKey",
        secretKey: "secretKey"
    });
    
    Now that the pubnub object is instantiated the client will be able to access the PAM functions. The pubnub object will use the secretKey to sign all PAM messages to the PubNub Network.
  6. var proxy = new HttpsProxyAgent('http://username:password@<ip:port>');
    
    var pubnub = new PubNub({ 
    	subscribeKey: 'demo', 
    	publishKey: 'demo', 
    	proxy: proxy 
    });
These functions are used to set/get a user ID on the fly.
To set/get UUID you can use the following method(s) in NodeJS V4 SDK
  1. ParameterTypeRequiredDescription
    uuid String YesUUID to set.
  2. This method doesn't take any arguments.

  3. This method doesn't take any arguments.

pubnub.setUUID("CustomUUID")
pubnub.getUUID();
PubNub.generateUUID();
  1. var channel = PubNub.generateUUID();
    
    pubnub.subscribe({
        channels: [channel]
    })
  2. var newUUID = PubNub.generateUUID();
    
    var pubnub = new PubNub ({ 
        uuid: newUUID, 
        subscribeKey: "mySubscribeKey",
        publishKey: "myPublishKey",
        secretKey: "secretKey"
    });
  3. var randomAuthKey = PubNub.generateUUID();
       
    var pubnub = new PubNub ({
    	authKey: randomAuthKey, 
    	subscribeKey: "mySubscribeKey",
    	publishKey: "myPublishKey",
    	secretKey: "secretKey"
    });
This function provides the capability to reset a user's auth Key.
Typically auth Key is specified during initialization for PubNub Access Manager enabled applications. In the event that auth Key has expired or a new auth Key is issued to the client from a Security Authority, the new auth Key can be sent using setAuthKey().
To Set Authentication Key you can use the following method(s) in the NodeJS V4 SDK
  1. ParameterTypeRequiredDescription
    key String YesAuth key to set.
pubnub.setAuthKey("my_authkey");
None.
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.
To set/get filters you can use the following methods.
  1. ParameterTypeRequiredDescription
    filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression.
  2. This method doesn't take any arguments.

pubnub.setFilterExpression("such=wow");
pubnub.getFilterExpression();

Go to Publish & Subscribe