Configuration API for JavaScript SDK

The PubNub JavaScript SDK creates a client with new PubNub(configuration) from the settings in PubNubConfiguration. A client can't connect to PubNub without a subscribe key and a User ID. Setter methods such as setUserId() and setAuthKey() change some settings on an existing client.

Getters and setters on this page are synchronous. Each returns its value or nothing, never a promise. To install the SDK or load it from a script tag, see Environment setup.

Initialization​

new PubNub(configuration) creates a PubNub client for JavaScript from the settings in PubNubConfiguration.

Reuse the client instance

Create one PubNub client and reuse it for the lifetime of the user or session. Don't call new PubNub(configuration) for every publish or operation. When a client is no longer needed, call destroy() to release its connections and background resources.

For more information, refer to Reuse the client instance.

#

#

required
configuration required#
Type: PubNubConfiguration
Default: no default
The settings that the new client uses. For each setting, see Configuration.

Initialize with your subscribeKey, publishKey, and a userId that identifies the client.

Initialization errors​

The constructor throws a PubNubError for these inputs. The SDK does not send any request first.

ConditionError message
userId is omittedPubNub client configuration error: 'userId' not set
userId is empty or only whitespacePubNub client configuration error: 'userId' is empty
userId and uuid are both setPubNub client configuration error: use only 'userId'

Server operations​

A Node.js server can run several clients of the JavaScript SDK on the same machine and does not authenticate end users. A server that grants Access Manager permissions initializes its client with secretKey. A client initialized with the secret key signs its Access Manager requests with that key and has access to every channel and channel group. The pre-built web bundle, including the copy on the PubNub content delivery network (CDN), disables the Access Manager module at build time, so secretKey has no effect in a browser. See the Security tab in Initialization.

Syntax

1new PubNub(configuration: PubNubConfiguration): PubNub;

Configuration​

PubNubConfiguration holds the settings that control a PubNub client for JavaScript, including your keys and the User ID.

required
subscribeKey required#
Type: string
Default: no default
The subscribe key of your keyset, from the Admin Portal.
publishKey#
Type: string
Default: no default
The publish key of your keyset, from the Admin Portal. Operations that publish, such as publish() and signal(), need the publish key.
userId required#
Type: string
Default: no default
A User ID is the string that identifies a person or a server process to PubNub. One person uses the same User ID on all of their devices. A User ID cannot exceed 92 UTF-8 characters. Without a User ID, the client can't connect to PubNub.

A user or device should keep one User ID for its whole lifetime instead of getting a new one on each connection. Other clients can see a User ID, for example in presence events and as the publisher of a message. A User ID must not contain an email address, a username, or other personally identifiable information. The User ID should be a value that you can replace without the user's involvement.

The constructor throws a PubNubError when userId is missing or empty. See Initialization errors.
secretKey#
Type: string
Default: no default
The secret key of your keyset, from the Admin Portal. secretKey works only in Node.js builds. See Server operations.
authKey#
Type: string
Default: no default
The Access Manager authentication key that the client sends with its requests. For how Access Manager grants permissions, see Access Manager. A token set with setToken() takes precedence over authKey in every request. Change authKey later with setAuthKey().
ssl#
Type: boolean
Default: true
Whether the client sends requests over HTTPS instead of HTTP.
origin#
Type: string or string[]
Default: no default
The domain name that the client sends requests to. To use your own domain, request a custom domain. When omitted, the SDK uses the subdomains ps1.pndsn.com to ps20.pndsn.com.
presenceTimeout#
Type: number
Default: 300
How long, in seconds, PubNub keeps the client present without a heartbeat. If no heartbeat arrives in that time, PubNub marks the client offline and emits a timeout event on the presence channel. Setting presenceTimeout also sets heartbeatInterval to half the presence timeout minus one second. The derived value replaces any heartbeatInterval in the same configuration. The SDK replaces a value above 320 with 320 and logs a console warning.
heartbeatInterval#
Type: number
Default: no default
How often, in seconds, the client sends an explicit presence heartbeat. By default, only explicit heartbeats keep a client present. Subscribe requests count as heartbeats only when the keyset's Subscribe heartbeats (implicit) setting is on. The recommended value is half the presence timeout minus one second.

When neither heartbeatInterval nor presenceTimeout is set, the client sends no periodic heartbeats. With the standardized workflows, the client still sends one heartbeat each time it subscribes. Setting presenceTimeout replaces this value.
suppressLeaveEvents#
Type: boolean
Default: false
Whether the client stops sending leave requests when it unsubscribes. In the JavaScript SDK, suppressLeaveEvents applies with the legacy subscription manager. With the standardized workflows, the setting applies only when heartbeatInterval or presenceTimeout is set.
maintainPresenceState#
Type: boolean
Default: true
Whether the client includes the presence state that you set with setState() when it subscribes and in each presence heartbeat. maintainPresenceState applies only when enableEventEngine is true. For the method, see pubnub.setState().
enableEventEngine#
Type: boolean
Default: true
Whether the client runs subscribe and presence on the standardized workflows. The setting also decides which statuses the client emits. To keep the legacy subscription manager, set enableEventEngine: false. With true, the SDK ignores autoNetworkDetection.

For the statuses of each workflow and how to migrate, see Status events.
requestMessageCountThreshold#
Type: number
Default: 100
The number of messages in one subscribe response at which the client emits PNRequestMessageCountExceededCategory. requestMessageCountThreshold applies only when enableEventEngine is false.
retryConfiguration#
Type: RequestRetryPolicy
Default: PubNub.ExponentialRetryPolicy({ minimumDelay: 2, maximumDelay: 150, maximumRetry: 6 })
The policy that decides whether and how the client retries a failed request: none, linear, or exponential. For how retries work, see Reconnection policies. See retryConfiguration. You can exclude groups of endpoints from the policy, so that the client never retries their requests. retryConfiguration works in the browser and in Node.js.

Available values:
  • PubNub.NoneRetryPolicy()
  • PubNub.LinearRetryPolicy({ delay, maximumRetry, excluded })
  • PubNub.ExponentialRetryPolicy({ minimumDelay, maximumDelay, maximumRetry, excluded })
excluded takes an array of Endpoint enum values, for example, excluded: [PubNub.Endpoint.MessageSend].

The default policy applies only when enableEventEngine is true. It excludes the MessageSend, Presence, Files, MessageStorage, ChannelGroups, DevicePushNotifications, AppContext, and MessageReactions endpoint groups. The client retries subscribe requests and any request outside those groups, such as time().

Set retry limits explicitly

The JavaScript SDK doesn't enforce upper bounds on maximumRetry or maximumDelay.

Without limits, misconfigured policies may cause excess network traffic, battery drain, or usage spikes. Always choose values suited to your app.

cryptoModule#
Type: PubNub.CryptoModule.legacyCryptoModule({ cipherKey, useRandomIVs })

PubNub.CryptoModule.aesCbcCryptoModule({cipherKey})
Default: no default
The crypto module that encrypts and decrypts messages and files. Both modules take cipherKey, and the legacy module also takes useRandomIVs. See cryptoModule.
logLevel#
Type: LogLevel
Default: LogLevel.None
The lowest severity of log messages that the SDK records.

Available values:
  • LogLevel.Trace
  • LogLevel.Debug
  • LogLevel.Info
  • LogLevel.Warn
  • LogLevel.Error
See Logging.
loggers#
Type: Logger[]
Default: []
Custom logger implementations that receive the SDK's log messages. See Logging.
keepAlive#
Type: boolean
Default: false
Only the Node.js transport uses this setting. true keeps idle connections open for reuse, within the limits in keepAliveSettings. With false, the Node.js transport disables HTTP/1.1 pipelining but still pools and reuses sockets.
keepAliveSettings#
Type: any
Default: no default
Connection settings that apply when keepAlive is true.

keepAliveMsecs: (Number) the delay, in milliseconds, before the first TCP keep-alive probe on a socket.
timeout: (Number) how long, in milliseconds, an idle socket stays open. When you omit keepAliveSettings, the SDK uses 30000.
maxSockets: (Number) the maximum number of sockets per host.
maxFreeSockets: (Number) has no effect on the Node.js transport.
transport#
Type: string
Default: fetch
transport works only in the browser. The API the SDK uses for network requests: fetch or xhr (XMLHttpRequest). If the browser has no fetch, the SDK falls back to xhr. A Shared Worker always uses fetch.
restore#
Type: boolean
Default: true
How the client behaves when the network goes down. restore works only in the browser. restore applies only when listenToBrowserNetworkEvents is true.

  • true moves the client into the disconnected state without sending leave events. The SDK keeps the current timetoken and active channel list, so it can catch up on missed messages when the connection returns.
  • false resets the timetoken and active channel list. To keep subscriptions, subscribe again when PNNetworkUpCategory fires. false restores the behavior from before v11.0.0.
autoNetworkDetection#
Type: boolean
Default: false
Whether the SDK emits the PNNetworkDownCategory and PNNetworkUpCategory statuses when the network status changes. See browser-specific statuses. autoNetworkDetection works in the browser and in Node.js. autoNetworkDetection applies only when enableEventEngine is false.
listenToBrowserNetworkEvents#
Type: boolean
Default: true
Whether the SDK listens for the browser's reachability events, emits the PNNetworkDownCategory and PNNetworkUpCategory statuses, and tries to reconnect when the network status changes. listenToBrowserNetworkEvents works only in the browser.

A browser can miss a network change, such as a switch from Wi-Fi to LAN, or the client can fail to reconnect. In either case, set listenToBrowserNetworkEvents to false so that the SDK reconnection logic takes over.
subscriptionWorkerUrl#
Type: string
Default: no default
The URL of the shared worker. subscriptionWorkerUrl works only in the browser. The worker URL must share the origin of the page that uses the worker. To host and version the worker, see Share subscriptions across browser tabs.

retryConfiguration​

To change how the SDK retries failed requests, pass a policy to retryConfiguration. The table above lists the default policy and the requests it applies to.

To wait the same time between retries, use a linear policy:

To double the wait after each retry, use an exponential policy:

To turn retries off, use the none policy:

cryptoModule​

PubNub SDKs include two crypto modules: a legacy module with 128-bit cipher key entropy, and the recommended AES-CBC module. The AES-CBC module uses 256-bit Advanced Encryption Standard (AES) encryption in cipher block chaining (CBC) mode. As of SDK version 7.4.0, you can configure the algorithms that cryptoModule uses. For background, see Message Encryption and File Encryption.

To use 256-bit AES-CBC encryption, set cryptoModule to PubNub.CryptoModule.aesCbcCryptoModule({ cipherKey }). For methods that encrypt and decrypt files and part of a message, see Encryption.

In Node.js and browsers, the PubNub.CryptoModule.aesCbcCryptoModule() and PubNub.CryptoModule.legacyCryptoModule() helpers also decrypt AES-GCM (ACGM) data that other PubNub SDKs write. React Native can't decrypt AES-GCM data. To add AES-GCM decryption to a custom module, see Decrypt AES-GCM data.

HTTP/2​

The Node.js transport of the JavaScript SDK, built on undici, negotiates HTTP/2 as of SDK version 12.0.0. In browsers and React Native, protocol negotiation, including HTTP/2, is outside the SDK's control.

When TLS Application-Layer Protocol Negotiation (ALPN) on a socket selects h2, undici speaks HTTP/2. undici falls back to HTTP/1.1 when an origin advertises only HTTP/1.

To see which protocol a request used, check the SDK's debug-level network response logs on Node.js. See Logging. For HTTP/2 support across PubNub origins, see Data transport and protocols.

Syntax

1type PubNubConfiguration = {
2 subscribeKey: string;
3 publishKey?: string;
4 userId: string;
5 secretKey?: string;
6 authKey?: string;
7 ssl?: boolean;
8 origin?: string | string[];
9 presenceTimeout?: number;
10 heartbeatInterval?: number;
11 suppressLeaveEvents?: boolean;
12 maintainPresenceState?: boolean;
13 enableEventEngine?: boolean;
14 requestMessageCountThreshold?: number;
15 retryConfiguration?: RequestRetryPolicy;
show all 25 lines

Set user ID​

setUserId() changes the User ID of a PubNub client for JavaScript after the client is created. To set the first User ID, use userId in Configuration.

#

#

required
userId required#
Type: string
The new User ID of the client.

Returns​

setUserId() returns nothing.

Syntax

1pubnub.setUserId(userId: string): void;

Get user ID​

getUserId() returns the current User ID of a PubNub client for JavaScript. getUserId() takes no arguments.

Returns​

getUserId() returns the current userId as a string.

Syntax

1pubnub.getUserId(): string;

Set authentication key​

setAuthKey() replaces the authentication key that a PubNub client for JavaScript sends with new requests. Call setAuthKey() when the current key expires or your server issues a new one. To set the first key, use authKey in Configuration.

A token set with setToken() takes precedence over authKey in every request.

required
authKey required#
Type: string
The authentication key to use with new requests.

Returns​

setAuthKey() returns nothing.

Syntax

1pubnub.setAuthKey(authKey: string): void;

Get authentication key​

getAuthKey() returns the current authentication key of a PubNub client for JavaScript, or undefined when it has none. getAuthKey() takes no arguments.

Returns​

getAuthKey() returns the current authentication key as a string | undefined.

Syntax

1pubnub.getAuthKey(): string | undefined;

Set filter expression​

setFilterExpression() sets the subscribe filter of a PubNub client for JavaScript. PubNub evaluates the filter on the server before it delivers a message, so messages that don't match never reach the client. For the expression syntax, see Subscribe filter expressions.

A subscribe filter is a property of the client, not of one subscription or channel, so it applies to every channel and channel group that client subscribes to.

required
filterExpression required#
Type: string or null
The filter expression to apply to the subscriptions of the client.

Returns​

setFilterExpression() returns nothing.

Syntax

1pubnub.setFilterExpression(filterExpression: string | null): void;

Get filter expression​

getFilterExpression() returns the current subscribe filter expression of a PubNub client for JavaScript, or undefined when it has none. getFilterExpression() takes no arguments.

Returns​

getFilterExpression() returns the current filter expression as a string | undefined.

Syntax

1pubnub.getFilterExpression(): string | undefined;

Destroy​

destroy() shuts down a PubNub client for JavaScript. Call destroy() when you no longer need the client.

destroy() invalidates all subscriptions and subscription sets and unsubscribes from all channels and channel groups. In React, call destroy() when a component unmounts.

isOffline#
Type: boolean
Default: false
Whether to skip the leave request because the client is already offline. true skips it.

Returns​

destroy() returns nothing.

Syntax

1pubnub.destroy(isOffline?: boolean): void;

Deprecated parameters and methods​

Deprecated JavaScript configuration parameters still work, and each one has a current replacement. The deprecated stop() method is an alias of destroy().

For apps that still set deprecated parameters or call stop(), Configuration API: deprecated parameters and stop() method for JavaScript SDK lists each one with its replacement.

Was this page useful?

Last updated on