PubNub LogoDocs
SupportContact SalesLoginTry Our APIs

›API Reference

javascript

  • Getting Started
  • API Reference

    • Configuration
    • Publish & Subscribe
    • Presence
    • Access Manager
    • Channel Groups
    • Message Persistence
    • Mobile Push
    • Objects
    • Files
    • Message Actions
    • Miscellaneous
  • Status Events
  • Troubleshooting
  • Change Log
  • Feature Support
  • Platform Support

Configuration API for PubNub JavaScript SDK

JavaScript V4 complete API reference for building real-time applications on PubNub, including basic usage and sample code.

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

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.6.0.0.js"></script>

Initialization

Description

Use this method to initialize the PubNub Client API context and establish account-level credentials such as publish and subscribe keys. You can create an account and get your keys from the Admin Portal.

Method(s)

To Initialize PubNub, you can use the following method(s) in the JavaScript V4 SDK:

PubNub({String subscribeKey, String publishKey, String cipherKey, String authKey, Boolean logVerbosity, String uuid, Boolean ssl, String origin, Number presenceTimeout, Number heartbeatInterval, Boolean restore, Boolean keepAlive, Object keepAliveSettings, Boolean useInstanceId, Boolean suppressLeaveEvents, Number requestMessageCountThreshold, Boolean autoNetworkDetection, Boolean listenToBrowserNetworkEvents})
ParameterTypeRequiredDefaultsDescription
Operation ArgumentsHashYesA hash of arguments.
subscribeKeyStringYesSpecifies the subscribeKey to be used for subscribing to a channel. This key can be specified at initialization or along with a subscribe().
publishKeyStringOptionalSpecifies the publishKey to be used for publishing messages to a channel. This key can be specified at initialization or along with a publish().
cipherKeyStringOptionalIf passed, will encrypt the payloads.
authKeyStringOptionalIf PAM enabled, this key will be used on all requests.
logVerbosityBooleanOptionalfalselog HTTP information.
uuidStringYesUUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.
sslBooleanOptionaltrue for v4.20.0 onwards,
false before v4.20.0
If set to true, requests will be made over HTTPS.
originStringOptionalps.pndsn.comIf a custom domain is required, SDK accepts it here.
presenceTimeoutNumberOptional300How long the server will consider the client alive for presence.The value is in seconds.
heartbeatIntervalNumberOptionalNot SetHow often the client will announce itself to server.The value is in seconds.
restoreBooleanOptionalfalsetrue to allow catch up on the front-end applications.
keepAliveBooleanOptionalfalseIf set to true, SDK will use the same TCP connection for each HTTP request, instead of opening a new one for each new request.
keepAliveSettingsObjectOptionalkeepAliveMsecs: 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.
suppressLeaveEventsBooleanOptionalfalseWhen true the SDK doesn't send out the leave requests.
requestMessageCountThresholdNumberOptional100PNRequestMessageCountExceededCategory is thrown when the number of messages into the payload is above of requestMessageCountThreshold.
autoNetworkDetectionBooleanOptionalfalseThis flag announces when the network is down or up using the states PNNetworkDownCategory and 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 allows the SDK reconnection logic to take over.
useRandomIVsBooleanOptionaltrueWhen true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload.
Disabling random initialization vector

Disable random initialization vector (IV) only for backward compatibility (<4.31.0) with existing applications. Never disable random IV on new applications.

Basic Usage

Applications can initialize the PubNub object by passing the subscribeKey and publishKey keys from your account. Each client should also pass a UUID that represents the user or the device that connects to PubNub.

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    cipherKey: "myCipherKey",
    authKey: "myAuthKey",
    logVerbosity: true,
    uuid: "myUniqueUUID",
    ssl: true,
    presenceTimeout: 130
});

Server Operations

For servers connecting to PubNub, setting a UUID is different than for a client device as there can be multiple instances of the server on the same machine and there is no "authentication" process for a server (at least not like an end user).

The API can be initialized with the secretKey if the server needs to administer PAM permissions for client applications. When you initialize PubNub 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 channels or channel groups. The servers get all access on all channels and channel groups.

Note

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

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    uuid: "myUniqueUUID",
    secretKey: "secretKey",
    heartbeatInterval: 0
});

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.

Other Examples

  1. Initialization for a Read-Only client:

    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:

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    // Initialize for Read Only Client
    
    var pubnub = new PubNub({
        subscribeKey: "mySubscribeKey",
        uuid: "myUniqueUUID"
    });
    
  2. Initializing with SSL Enabled:

    This examples demonstrates how to enable PubNub Transport Layer Encryption with TLS(formerly known as 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.

    Note

    Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

    var pubnub = new PubNub({
        subscribeKey: "mySubscribeKey",
        publishKey: "myPublishKey",
        cipherKey: "myCipherKey",
        authKey: "myAuthKey",
        logVerbosity: true, // set false for production
        uuid: "myUniqueUUID",
        ssl: true
    });
    

Event Listeners

Description

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

Listeners should be added before calling the method.

Adding Listeners

pubnub.addListener({
  // Messages
  message: function (m) {
    const channelName = m.channel; // Channel on which the message was published
    const channelGroup = m.subscription; // Channel group or wildcard subscription match (if exists)
    const pubTT = m.timetoken; // Publish timetoken
    const msg = m.message; // Message payload
    const publisher = m.publisher; // Message publisher
  },
  // Presence
  presence: function (p) {
    const action = p.action; // Can be join, leave, state-change, or timeout
    const channelName = p.channel; // Channel to which the message belongs
    const occupancy = p.occupancy; // Number of users subscribed to the channel
    const state = p.state; // User state
    const channelGroup = p.subscription; //  Channel group or wildcard subscription match, if any
    const publishTime = p.timestamp; // Publish timetoken
    const timetoken = p.timetoken; // Current timetoken
    const uuid = p.uuid; // UUIDs of users who are subscribed to the channel
  },
  // Signals
  signal: function (s) {
    const channelName = s.channel; // Channel to which the signal belongs
    const channelGroup = s.subscription; // Channel group or wildcard subscription match, if any
    const pubTT = s.timetoken; // Publish timetoken
    const msg = s.message; // Payload
    const publisher = s.publisher; // Message publisher
  },
  objects: (objectEvent) => {
    const channel = objectEvent.channel; // Channel to which the event belongs
    const channelGroup = objectEvent.subscription; // Channel group
    const timetoken = objectEvent.timetoken; // Event timetoken
    const publisher = objectEvent.publisher; // UUID that made the call
    const event = objectEvent.event; // Name of the event that occurred
    const type = objectEvent.type; // Type of the event that occurred
    const data = objectEvent.data; // Data from the event that occurred
  },
  messageAction: function (ma) {
    const channelName = ma.channel; // Channel to which the message belongs
    const publisher = ma.publisher; // Message publisher
    const event = ma.event; // Message action added or removed
    const type = ma.data.type; // Message action type
    const value = ma.data.value; // Message action value
    const messageTimetoken = ma.data.messageTimetoken; // Timetoken of the original message
    const actionTimetoken = ma.data.actionTimetoken; // Timetoken of the message action
  },
  file: function (event) {
    const channelName = event.channel; // Channel to which the file belongs
    const channelGroup = event.subscription; // Channel group or wildcard subscription match (if exists)
    const publisher = event.publisher; // File publisher
    const timetoken = event.timetoken; // Event timetoken

    const message = event.message; // Optional message attached to the file
    const fileId = event.file.id; // File unique id
    const fileName = event.file.name;// File name
    const fileUrl = event.file.url; // File direct URL
  },
  status: function (s) {
    const affectedChannelGroups = s.affectedChannelGroups; // Array of channel groups affected in the operation
    const affectedChannels = s.affectedChannels; // Array of channels affected in the operation
    const category = s.category; // Returns PNConnectedCategory
    const operation = s.operation; // Returns PNSubscribeOperation
    const lastTimetoken = s.lastTimetoken; // Last timetoken used in the subscribe request (type long)
    const currentTimetoken = s.currentTimetoken; /* Current timetoken fetched in subscribe response,
                                                * to be used in the next request (type long) */
    const subscribedChannels = s.subscribedChannels; // Array of all currently subscribed channels
  },
});

Removing Listeners

var existingListener = {
  message: function () {
  },
};

pubnub.removeListener(existingListener);

Listener status events

CategoryDescription
PNNetworkUpCategoryThe SDK detected that the network is online.
PNNetworkDownCategoryThe SDK announces this when a connection isn't available, or when the SDK isn't able to reach the PubNub Data Stream Network.
PNNetworkIssuesCategoryA subscribe event experienced an exception when running. The SDK isn't able to reach the PubNub Data Stream Network. This may be due to many reasons, such as: the machine or device isn't connected to the internet; the internet connection has been lost; your internet service provider is having trouble; or, perhaps the SDK is behind a proxy.
PNReconnectedCategoryThe SDK was able to reconnect to PubNub.
PNConnectedCategorySDK subscribed with a new mix of channels. This is fired every time the channel or channel group mix changes.
PNAccessDeniedCategoryPAM permission failure.
PNMalformedResponseCategoryJSON parsing crashed.
PNBadRequestCategoryThe server responded with a bad response error because the request is malformed.
PNDecryptionErrorCategoryIf using decryption strategies and the decryption fails.
PNTimeoutCategoryFailure to establish a connection to PubNub due to a timeout.
PNRequestMessageCountExceedCategoryThe SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold.
PNUnknownCategoryReturned when the subscriber gets a non-200 HTTP response code from the server.

UUID

Description

A UUID (Universal Unique Identifier) is a required unique alphanumeric identifier used to identify the client to the PubNub platform. Each client must pass a UUID that represents the user or the device that connects to PubNub.

Setting the UUID

Set the UUID parameter when you instantiate a PubNub instance (i.e., new PubNub()). It is important that your application reuse the UUID on each device instead of generating a new UUID on each connection.

Note

Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UUID, you won't be able to connect to PubNub.

var pubnub = new PubNub({
    subscribeKey: "mySubscribeKey",
    publishKey: "myPublishKey",
    uuid: "myUniqueUUID"
});

You can also call the following method to explicitly set the UUID:

pubnub.setUUID(string)
ParameterTypeRequiredDescription
uuidStringYesUUID to set.
pubnub.setUUID("myUniqueUUID")

Saving the UUID

Providing a value for the uuid parameter in the PubNub object initialization will result in that value getting saved in the browser's localStorage key (described above) automatically by the PubNub SDK. You may implement a different local caching strategy, as required.

Consider the following when implementing a UUID reuse strategy:

  1. On your server, generate a UUID the when a user creates a user profile (user registration process). You can generate this with the SDK, or by another method of your choosing.
  2. Pass the UUID back to the user upon successful login (authentication process).
  3. Persist the UUID on the device where it can be retrieved the next time the PubNub instance is instantiated. The PubNub instance might be instantiated multiple times as the app is left and re-entered, and you may not require a login with each new session.

Getting the UUID

Use this method to get the current UUID set on your application.This method doesn't take any arguments.

pubnub.getUUID();
Note

Each PubNub SDK provides a UUID generator API (for example, generateUUID). It is not required that you use this API to create a UUID and this format of the UUID is not required (any string will do up to 64 characters). Just consider that whatever you use will be visible to other users (if a user peeks behind the scenes using the browser console or other tools), so you should not use a username or email as the UUID. The UUID should be something that can be easily replaced as required without user interaction or even knowledge that it has happened.

Generating the UUID

Use this method to generate a UUID.

PubNub.generateUUID();

Authentication Key

Description

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().

Property

To Set Authentication Key you can use the following method(s) in the JavaScript V4 SDK

pubnub.setAuthKey(string)
ParameterTypeRequiredDescription
keyStringYesAuth key to set.

Basic Usage

pubnub.setAuthKey("my_authkey");

Returns

None.

Filter Expression

Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-

Description

Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.

To set/get filters you can use the following method. To learn more about filtering, refer to the Publish Messages documentation.

Method(s)

  1. pubnub.setFilterExpression(String filterExpression)
    
    ParameterTypeRequiredDescription
    filterExpressionStringYesPSV2 feature to subscribe with a custom filter expression.
  2. pubnub.getFilterExpression()
    

    This method doesn't take any arguments.

Basic Usage

Set Filter Expression

pubnub.setFilterExpression("such=wow");

Get Filter Expression

pubnub.getFilterExpression();
← Getting StartedPublish & Subscribe →
  • Initialization
    • Description
    • Method(s)
    • Basic Usage
    • Server Operations
    • Other Examples
  • Event Listeners
    • Description
  • UUID
    • Description
    • Setting the UUID
    • Saving the UUID
    • Getting the UUID
    • Generating the UUID
  • Authentication Key
    • Description
    • Property
    • Basic Usage
    • Returns
  • Filter Expression
    • Description
    • Method(s)
    • Basic Usage
© PubNub Inc. - Privacy Policy