Configuration API for PubNub JavaScript SDK

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

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

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

Initialization

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 SDK:

pubnub.PubNub({
subscribeKey: string,
publishKey: string,
userId: string,
authKey: string,
logVerbosity: boolean,
ssl: boolean,
origin: string,
presenceTimeout: number,
heartbeatInterval: number,
restore: boolean,
keepAlive: boolean,
keepAliveSettings: any,
useInstanceId: boolean,
suppressLeaveEvents: boolean,
show all 22 lines
ParameterTypeRequiredDefaultDescription
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().
userIdstringYesuserId to use. You should set a unique userId to identify the user or the device that connects to PubNub.

It's a UTF-8 encoded string of up to 64 alphanumeric characters.

If you don't set the userId, you won't be able to connect to PubNub.
authKeystringOptionalIf Access Manager enabled, this key will be used on all requests.
logVerbositybooleanOptionalfalseLog HTTP information.
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.
keepAliveSettingsanyOptionalkeepAliveMsecs: 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.
useInstanceIdbooleanOptionalfalseWhether or not to include the PubNub object instance ID in outgoing requests.
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.
cryptoModulePubNub.CryptoModule.legacyCryptoModule({ cipherKey, useRandomIVs })

PubNub.CryptoModule.aesCbcCryptoModule({cipherKey})
OptionalNoneThe cryptography module used for encryption and decryption of messages and files. Takes the cipherKey and useRandomIVs parameters as arguments.

For more information, refer to the cryptoModule section.
cipherKeystringOptionalThis way of setting this parameter is deprecated, pass it to cryptoModule instead.

If passed, will encrypt the payloads.
useRandomIVsbooleanOptionaltrueThis way of setting this parameter is deprecated, pass it to cryptoModule instead.

When 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.
uuidstringYesThis parameter is deprecated, use userId instead.

UUID 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.
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.

cryptoModule

cryptoModule provides encrypt/decrypt functionality for messages and files. From the 7.3.3 release on, you can configure how the actual encryption/decryption algorithms work.

Each PubNub SDK is bundled with two ways of encryption: the legacy encryption with 128-bit cipher key entropy and the recommended 256-bit AES-CBC encryption. For more general information on how encryption works, refer to the Message Encryption and File Encryption sections.

If you do not explicitly set the cryptoModule in your app and have the cipherKey and useRandomIVs params set in PubNub config, the client defaults to using the legacy encryption.

Legacy encryption with 128-bit cipher key entropy

You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.

cryptoModule configuration

To configure the cryptoModule to encrypt all messages/files, you can use the following methods in the Javascript SDK:

// encrypts using 256-bit AES-CBC cipher (recommended)
// decrypts data encrypted with the legacy and the 256 bit AES-CBC ciphers
const pn = new PubNub({
cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'});
)};

// encrypts with 128-bit cipher key entropy (legacy)
// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers
const pn = new PubNub({
cryptoModule: PubNub.CryptoModule.legacyCryptoModule({cipherKey: 'pubnubenigma', useRandomIVs: true});
)};

Your client can decrypt content encrypted using either of the modules. This way, you can interact with historical messages or messages sent from older clients while encoding new messages using the more secure 256-bit AES-CBC cipher.

Older SDK versions

Apps built using the SDK versions lower than 7.3.3 will not be able to decrypt data encrypted using the 256-bit AES-CBC cipher. Make sure to update your clients or encrypt data using the legacy algorithm.

Basic Usage

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

Required userId

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

var pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'}),
authKey: "myAuthKey",
logVerbosity: true,
userId: "myUniqueUserId",
ssl: true,
presenceTimeout: 130
});

Server Operations

For servers connecting to PubNub, setting a userId 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 Access Manager 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 to all channels and channel groups.

Secure your secretKey

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 applications or other server-side platforms.

Required userId

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

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

Now that the pubnub object is instantiated, the client will be able to access the Access Manager functions. The pubnub object will use the secretKey to sign all Access Manager messages to the PubNub Network.

Other Examples

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:

Required userId

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

// Initialize for Read Only Client

var pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId"
});

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.

Required userId

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

var pubnub = new PubNub({
subscribeKey: "mySubscribeKey",
publishKey: "myPublishKey",
cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'}),
authKey: "myAuthKey",
logVerbosity: true, // set false for production
userId: "myUniqueUserId",
ssl: true
});

Event Listeners

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

Listeners should be added before calling the method.

Add 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
show all 71 lines

Remove 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.
PNAccessDeniedCategoryAccess Manager 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.

User ID

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

Set User ID

Set the userId parameter when you instantiate a PubNub instance (new PubNub()). It's important that your application reuse the userId on each device instead of generating a new userId on each connection.

Required userId

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

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

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

pubnub.setUserId(string)
ParameterTypeRequiredDescription
userIdStringYesuserId to set.
pubnub.setUserId("myUniqueUserId")

Save User ID

Providing a value for the userId 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 userId reuse strategy:

  1. On your server, generate a userId 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 userId back to the user upon successful login (authentication process).
  3. Persist the userId 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.

Get User ID

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

pubnub.getUserId();
Required userId recommendation

Remember that whatever user ID you use is 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 userId. The userId should be something that can be easily replaced as required without user interaction or even knowledge that it has happened.

Authentication Key

This function provides the capability to reset a user's auth Key.

Typically auth Key is specified during initialization for 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 SDK

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

Basic Usage

pubnub.setAuthKey("my_authkey");

Returns

None.

Filter Expression

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

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 or get message filters, you can use the following method. To learn more about filtering, refer to the Publish Messages documentation.

Method(s)

pubnub.setFilterExpression(
filterExpression: string
)
ParameterTypeRequiredDescription
filterExpressionstringYesPSV2 feature to subscribe with a custom filter expression.
pubnub.getFilterExpression()

This method doesn't take any arguments.

Basic Usage

Set Filter Expression

pubnub.setFilterExpression("such=wow");

Get Filter Expression

pubnub.getFilterExpression();

Generate UUID (deprecated)

Alternative method

This method is deprecated. Use Set User ID instead.

Use this method to generate a UUID.

PubNub.generateUUID();
Last updated on