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.
#
-
The client requires
subscribeKeyanduserId. Get your keys from the Admin Portal. -
The constructor throws a
PubNubErrorwhenuserIdis missing or empty. See Initialization errors. -
For the rules a
userIdmust follow, see theuserIdrow in Configuration.
#
PubNub SDKs connect over TLS 1.2 by default, except the Lua SDK and the unsupported Twisted SDK, where you set ssl to true.
The secret key grants privileged access to your PubNub application. It must remain on a trusted server and must never be included in client applications.
In JavaScript, set secretKey only in server code, such as a Node.js application. 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. In a browser, grantToken() throws Grant Token error: PAM module disabled, and requests carry no signature. Grant tokens on a Node.js server and pass them to the client with setToken(). To enable the module in a custom bundle, set PAM_MODULE=enabled as described in Build a custom bundle.
configurationrequired#- The settings that the new client uses. For each setting, see Configuration.
Sample code
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.
| Condition | Error message |
|---|---|
userId is omitted | PubNub client configuration error: 'userId' not set |
userId is empty or only whitespace | PubNub client configuration error: 'userId' is empty |
userId and uuid are both set | PubNub 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.
Other examples
Examples for Initialization
Syntax
1new PubNub(configuration: PubNubConfiguration): PubNub;
Basic usage
1
Basic usage (React)
In React, initialize PubNub inside a useEffect hook and hold the instance in a useRef so it is stable across renders. Destroy the client in the cleanup function to release connections when the component unmounts.
1
Server operations
1
Initialize a read-only client
Initialize a read-only client
A client that never publishes doesn't need publishKey.
1
Configuration
PubNubConfiguration holds the settings that control a PubNub client for JavaScript, including your keys and the User ID.
subscribeKeyrequired#- The subscribe key of your keyset, from the Admin Portal.
publishKey#- The publish key of your keyset, from the Admin Portal. Operations that publish, such as
publish()andsignal(), need the publish key. userIdrequired#- 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 aPubNubErrorwhenuserIdis missing or empty. See Initialization errors. secretKey#- The secret key of your keyset, from the Admin Portal.
secretKeyworks only in Node.js builds. See Server operations. authKey#- 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 overauthKeyin every request. ChangeauthKeylater withsetAuthKey(). ssl#- Whether the client sends requests over HTTPS instead of HTTP.
origin#- 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.comtops20.pndsn.com. presenceTimeout#- 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
timeoutevent on the presence channel. SettingpresenceTimeoutalso setsheartbeatIntervalto half the presence timeout minus one second. The derived value replaces anyheartbeatIntervalin the same configuration. The SDK replaces a value above320with320and logs a console warning. heartbeatInterval#- 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 neitherheartbeatIntervalnorpresenceTimeoutis set, the client sends no periodic heartbeats. With the standardized workflows, the client still sends one heartbeat each time it subscribes. SettingpresenceTimeoutreplaces this value. suppressLeaveEvents#- Whether the client stops sending leave requests when it unsubscribes. In the JavaScript SDK,
suppressLeaveEventsapplies with the legacy subscription manager. With the standardized workflows, the setting applies only whenheartbeatIntervalorpresenceTimeoutis set. maintainPresenceState#- Whether the client includes the presence state that you set with
setState()when it subscribes and in each presence heartbeat.maintainPresenceStateapplies only whenenableEventEngineistrue. For the method, seepubnub.setState(). enableEventEngine#- 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. Withtrue, the SDK ignoresautoNetworkDetection.
For the statuses of each workflow and how to migrate, see Status events. requestMessageCountThreshold#- The number of messages in one subscribe response at which the client emits
PNRequestMessageCountExceededCategory.requestMessageCountThresholdapplies only whenenableEventEngineisfalse. retryConfiguration#- 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.retryConfigurationworks in the browser and in Node.js.
Available values:PubNub.NoneRetryPolicy()PubNub.LinearRetryPolicy({ delay, maximumRetry, excluded })PubNub.ExponentialRetryPolicy({ minimumDelay, maximumDelay, maximumRetry, excluded })
excludedtakes an array ofEndpointenum values, for example,excluded: [PubNub.Endpoint.MessageSend].
The default policy applies only whenenableEventEngineistrue. It excludes theMessageSend,Presence,Files,MessageStorage,ChannelGroups,DevicePushNotifications,AppContext, andMessageReactionsendpoint groups. The client retries subscribe requests and any request outside those groups, such astime().Set retry limits explicitly
The JavaScript SDK doesn't enforce upper bounds on
maximumRetryormaximumDelay.Without limits, misconfigured policies may cause excess network traffic, battery drain, or usage spikes. Always choose values suited to your app.
cryptoModule#- The crypto module that encrypts and decrypts messages and files. Both modules take
cipherKey, and the legacy module also takesuseRandomIVs. SeecryptoModule. logLevel#- The lowest severity of log messages that the SDK records.
Available values:LogLevel.TraceLogLevel.DebugLogLevel.InfoLogLevel.WarnLogLevel.Error
keepAlive#- Only the Node.js transport uses this setting.
truekeeps idle connections open for reuse, within the limits inkeepAliveSettings. Withfalse, the Node.js transport disables HTTP/1.1 pipelining but still pools and reuses sockets. keepAliveSettings#- Connection settings that apply when
keepAliveistrue.
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 omitkeepAliveSettings, the SDK uses30000.
maxSockets: (Number)the maximum number of sockets per host.
maxFreeSockets: (Number)has no effect on the Node.js transport. transport#transportworks only in the browser. The API the SDK uses for network requests:fetchorxhr(XMLHttpRequest). If the browser has nofetch, the SDK falls back toxhr. A Shared Worker always usesfetch.restore#- How the client behaves when the network goes down.
restoreworks only in the browser.restoreapplies only whenlistenToBrowserNetworkEventsistrue.truemoves the client into thedisconnectedstate without sendingleaveevents. The SDK keeps the current timetoken and active channel list, so it can catch up on missed messages when the connection returns.falseresets the timetoken and active channel list. To keep subscriptions, subscribe again whenPNNetworkUpCategoryfires.falserestores the behavior from before v11.0.0.
autoNetworkDetection#- Whether the SDK emits the
PNNetworkDownCategoryandPNNetworkUpCategorystatuses when the network status changes. See browser-specific statuses.autoNetworkDetectionworks in the browser and in Node.js.autoNetworkDetectionapplies only whenenableEventEngineisfalse. listenToBrowserNetworkEvents#- Whether the SDK listens for the browser's reachability events, emits the
PNNetworkDownCategoryandPNNetworkUpCategorystatuses, and tries to reconnect when the network status changes.listenToBrowserNetworkEventsworks 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, setlistenToBrowserNetworkEventstofalseso that the SDK reconnection logic takes over. subscriptionWorkerUrl#- The URL of the shared worker.
subscriptionWorkerUrlworks 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.
Examples for Configuration
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 linesretryConfiguration
1
retryConfiguration (2)
1
retryConfiguration (3)
1
cryptoModule
1
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.
#
- Pass a non-empty string. An empty or non-string value throws an
Errorwith the messageMissing or invalid userId parameter. Provide a valid string userId. - The change does not affect REST API calls already in progress.
#
The SDK does not store the userId for you, so persist it on the device, for example in localStorage.
- When a user registers, generate a
userIdon your server. You can generate it with the SDK or any other method. - Return the
userIdto the user after a successful login. - Persist the
userIdon the device so the next PubNub instance can read it.
In a browser, anyone who inspects the page can read the userId. For the rules a userId must follow, see the userId row in Configuration.
userIdrequired#- The new User ID of the client.
Sample code
Returns
setUserId() returns nothing.Examples for Set user ID
Syntax
1pubnub.setUserId(userId: string): void;
Basic usage
1
Get user ID
getUserId() returns the current User ID of a PubNub client for JavaScript. getUserId() takes no arguments.
Sample code
Returns
getUserId() returns the current userId as a string.Examples for Get user ID
Syntax
1pubnub.getUserId(): string;
Basic usage
1
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.
authKeyrequired#- The authentication key to use with new requests.
Sample code
Returns
setAuthKey() returns nothing.Examples for Set authentication key
Syntax
1pubnub.setAuthKey(authKey: string): void;
Basic usage
1
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.
Sample code
Returns
getAuthKey() returns the current authentication key as a string | undefined.Examples for Get authentication key
Syntax
1pubnub.getAuthKey(): string | undefined;
Basic usage
1
Set filter expression
Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal.
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
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.
filterExpressionrequired#- The filter expression to apply to the subscriptions of the client.
Sample code
Returns
setFilterExpression() returns nothing.Examples for Set filter expression
Syntax
1pubnub.setFilterExpression(filterExpression: string | null): void;
Basic usage
1
Get filter expression
Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal.
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. See Enable the features your app calls.
getFilterExpression() returns the current subscribe filter expression of a PubNub client for JavaScript, or undefined when it has none. getFilterExpression() takes no arguments.
Sample code
Returns
getFilterExpression() returns the current filter expression as a string | undefined.Examples for Get filter expression
Syntax
1pubnub.getFilterExpression(): string | undefined;
Basic usage
1
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#- Whether to skip the leave request because the client is already offline.
trueskips it.
Sample code
Returns
destroy() returns nothing.Examples for Destroy
Syntax
1pubnub.destroy(isOffline?: boolean): void;
Basic usage
1
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.