---
source_url: https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration
title: Configuration API for JavaScript SDK
updated_at: 2026-06-04T11:11:54.905Z
sdk_name: PubNub JavaScript SDK
sdk_version: 11.0.1
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Configuration API for JavaScript SDK

PubNub JavaScript SDK, use the latest version: 11.0.1

Install:

```bash
npm install pubnub@11.0.1
```

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.

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

## Bundling

Use [Rollup](https://rollupjs.org/) or [Webpack](https://webpack.js.org/) to bundle only the modules you need.

Use our [configuration file](https://github.com/pubnub/javascript/blob/master/rollup.config.js) as a starting point.

:::note Access Manager module in web builds
The default web/browser build of the SDK disables the `PAM_MODULE` for security reasons. If you need PAM support in a browser context (for example, an internal admin tool), set `PAM_MODULE=enabled` when building a custom bundle. Be aware that this exposes the `secretKey` in client-side code — only do this for applications that are not publicly accessible.
:::

###### Rollup

1. Clone the PubNub JavaScript SDK repository to a directory of your choice.
2. In rollup.config.js, set enableTreeShaking to true.
3. Decide which modules to include. Disable the rest by setting environment variables, for example: export PRESENCE_MODULE=disabled PUBLISH_MODULE=disabled
4. Run rollup -c rollup.config.js --bundleConfigAsCjs. The bundle is in the _your_js_sdk_repo_dir_/upload directory.

###### Webpack

1. Clone the PubNub JavaScript SDK repository to a directory of your choice.
2. Create webpack.config.js based on the Rollup configuration file. Enable or disable modules with environment variables. const webpack = require('webpack'); module.exports = { // Other configuration... plugins: [ new webpack.DefinePlugin({ 'process.env.CRYPTO_MODULE': JSON.stringify(process.env.CRYPTO_MODULE ?? 'enabled'), 'process.env.SHARED_WORKER': JSON.stringify(process.env.SHARED_WORKER ?? 'enabled'), 'process.env.PUBLISH_MODULE': JSON.stringify(process.env.PUBLISH_MODULE ?? 'enabled'), 'process.env.SUBSCRIBE_MODULE': JSON.stringify(process.env.SUBSCRIBE_MODULE ?? 'enabled'), 'process.env.SUBSCRIBE_EVENT_ENGINE_MODULE': JSON.stringify(process.env.SUBSCRIBE_EVENT_ENGINE_MODULE ?? 'enabled'), 'process.env.SUBSCRIBE_MANAGER_MODULE': JSON.stringify(process.env.SUBSCRIBE_MANAGER_MODULE ?? 'enabled'), 'process.env.PRESENCE_MODULE': JSON.stringify(process.env.PRESENCE_MODULE ?? 'enabled'), 'process.env.PAM_MODULE': JSON.stringify(process.env.PAM_MODULE ?? 'enabled'), 'process.env.CHANNEL_GROUPS_MODULE': JSON.stringify(process.env.CHANNEL_GROUPS_MODULE ?? 'enabled'), 'process.env.MESSAGE_PERSISTENCE_MODULE': JSON.stringify(process.env.MESSAGE_PERSISTENCE_MODULE ?? 'enabled'), 'process.env.MOBILE_PUSH_MODULE': JSON.stringify(process.env.MOBILE_PUSH_MODULE ?? 'enabled'), 'process.env.APP_CONTEXT_MODULE': JSON.stringify(process.env.APP_CONTEXT_MODULE ?? 'enabled'), 'process.env.FILE_SHARING_MODULE': JSON.stringify(process.env.FILE_SHARING_MODULE ?? 'enabled'), 'process.env.MESSAGE_REACTIONS_MODULE': JSON.stringify(process.env.MESSAGE_REACTIONS_MODULE ?? 'enabled'), }), ],}; Webpack configurationAdd any other necessary configuration to webpack.config.js. See Webpack documentation.
3. Disable unnecessary modules by setting environment variables, for example: export PRESENCE_MODULE=disabled PUBLISH_MODULE=disabled
4. Run npx webpack --config webpack.config.js. Find the bundle in the output directory you configured.

## Initialization

Initialize the PubNub Client API and set 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:

```javascript
pubnub.PubNub({
  subscribeKey: string,
  publishKey: string,
  userId: string,
  authKey: string,
  logLevel: PubNub.LogLevel,
  ssl: boolean,
  origin: string | string[],
  presenceTimeout: number,
  heartbeatInterval: number,
  keepAlive: boolean,
  keepAliveSettings: any,
  suppressLeaveEvents: boolean,
  requestMessageCountThreshold: number,
  enableEventEngine: boolean
  restore: boolean,
  retryConfiguration: any
  autoNetworkDetection: boolean,
  listenToBrowserNetworkEvents: boolean
  maintainPresenceState: boolean
  cryptoModule: PubNub.CryptoModule
  subscriptionWorkerUrl: string
  // Deprecated, use userId instead
  uuid: string,
});
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| subscribeKey | string | Yes | `N/A` | Specifies the `subscribeKey` to be used for subscribing to a channel. This key can be specified at initialization or along with a `subscribe()`. |
| publishKey | string | Optional | `N/A` | Specifies the `publishKey` to be used for publishing messages to a channel. This key can be specified at initialization or along with a `publish()`. |
| userId | string | Yes | `N/A` | `userId` 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 92 alphanumeric characters.If you don't set the `userId`, you won't be able to connect to PubNub. |
| secretKey | string | Optional | `N/A` | Secret key from Admin Portal. When you initialize PubNub with `secretKey`, you get root permissions for [Access Manager](https://www.pubnub.com/docs/general/security/access-control). Only available in Node.js builds. The web/browser build disables the Access Manager module by default, so this parameter has no effect there. For more information, refer to [Server Operations](#server-operations). |
| authKey | string | Optional | `N/A` | The token returned from Access Manager that provides access to resources. For more information, refer to [Access Manager](https://www.pubnub.com/docs/general/security/access-control#authorization-flow). |
| logLevel | LogLevel | Optional | `LogLevel.None` | Enum defining the minimum level of severity for messages to be logged. Use this to adjust logging verbosity. Available values:LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.ErrorDefault: `LogLevel.None` (logging off). For more information, refer to [Logging](https://www.pubnub.com/docs/sdks/javascript/logging). |
| loggers | Logger[] | Optional | `[]` | Array of custom logger implementations. For more information, refer to [Logging](https://www.pubnub.com/docs/sdks/javascript/logging). |
| logVerbosity | boolean | Optional | `false` | This parameter is deprecated, use `logLevel` instead. Log HTTP information. For information on enabling logging and collecting logs for troubleshooting, see [Logging](https://www.pubnub.com/docs/sdks/javascript/logging). |
| ssl | boolean | Optional | `true for v4.20.0 onwards, false before v4.20.0` | If set to `true`, requests will be made over HTTPS. |
| origin | string | Optional | `ps.pndsn.com` | If a custom domain is required, SDK accepts it here. To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| presenceTimeout | number | Optional | `300` | How long the server considers the client alive for presence. The client sends periodic requests to stay active. If no heartbeat arrives within the timeout, the client is marked inactive and a "timeout" event is emitted on the [presence channel](https://www.pubnub.com/docs/general/presence/overview). |
| heartbeatInterval | number | Optional | `Not Set` | How often the client sends heartbeats. To shorten presence timeout, set roughly to `(presenceTimeout / 2) - 1`. Minimum value is `3`. |
| keepAlive | boolean | Optional | `false` | 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. |
| keepAliveSettings | any | Optional | `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. |
| suppressLeaveEvents | boolean | Optional | `false` | When `true` the SDK doesn't send out the leave requests. |
| requestMessageCountThreshold | number | Optional | `100` | Emits `PNRequestMessageCountExceededCategory` when payload message count exceeds the threshold. []() |
| enableEventEngine | boolean | Optional | `true` | Whether to use the standardized workflows for subscribe and presence, optimizing how the SDK internally handles these operations and which [statuses](https://www.pubnub.com/docs/sdks/javascript/status-events) it emits. Refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle) for more information. To keep the legacy subscription manager, set `enableEventEngine: false`. For migration guidance, see the [v11.0.0 migration guide](https://www.pubnub.com/docs/sdks/javascript/migration-guides/javascript-v11-migration-guide) and [Migrating to the new subscription loop](https://www.pubnub.com/docs/sdks/javascript/status-events#migrating-to-the-new-subscription-loop). This flag affects the following parameters: autoNetworkDetection is ignored when enableEventEngine is true, maintainPresenceState is automatically enabled when enableEventEngine is true |
| restore | boolean | Optional | `true` | This option is available only in the **browser environment** and requires [listenToBrowserNetworkEvents](#listen-to-browser-network-events) to be `true`. Controls the client state when the network goes down: true - moves the client into the disconnected state without sending leave events. Preserves the current timetoken and active channel list so the SDK can catch up on missed messages when connectivity is restored., false - resets the timetoken and active channel list. To keep subscriptions, re-subscribe manually when PNNetworkUpCategory fires. Set this to false to restore the pre-v11.0.0 behavior. |
| retryConfiguration | RequestRetryPolicy | Optional | `PubNub.ExponentialRetryPolicy({ minimumDelay: 2, maximumDelay: 150, maximumRetry: 6 }) applied to subscribe only when enableEventEngine: true` | This option is available in the **browser** and **Node.js environments**. Custom reconnection configuration parameters. You can specify one or more [endpoint groups](https://github.com/pubnub/javascript/blob/master/src/core/components/retryPolicy.ts) for which the retry policy won't be applied. `retryConfiguration: policy` is the type of policy to be used. Available values: PubNub.NoneRetryPolicy(), PubNub.LinearRetryPolicy({ delay, maximumRetry, excluded }), PubNub.ExponentialRetryPolicy({ minimumDelay, maximumDelay, maximumRetry, excluded })`excluded` takes an array of [Endpoint](https://github.com/pubnub/javascript/blob/master/src/core/components/retryPolicy.ts) enum values, for example, `excluded: [PubNub.Endpoint.MessageSend]`. For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#reconnection-policy). []() Set retry limits explicitlyThe 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. |
| autoNetworkDetection | boolean | Optional | `false` | This option is available in the **browser** and **Node.js environments**, only when [enableEventEngine](#enable-event-engine) is `false`. Whether the SDK should emit the [PNNetworkDownCategory](https://www.pubnub.com/docs/sdks/javascript/status-events#browser-specific-statuses) and [PNNetworkUpCategory](https://www.pubnub.com/docs/sdks/javascript/status-events#browser-specific-statuses) statuses on network status change. []() |
| listenToBrowserNetworkEvents | boolean | Optional | `true` | This option is available only in the **browser environment**. Whether the SDK should emit the [PNNetworkDownCategory](https://www.pubnub.com/docs/sdks/javascript/status-events#browser-specific-statuses) and [PNNetworkUpCategory](https://www.pubnub.com/docs/sdks/javascript/status-events#browser-specific-statuses) statuses, listen for the browser reachability events, and try to reconnect on network status change. If the browser fails to detect the network changes from WiFi to LAN or you get reconnection issues, set the flag to `false`. This allows the SDK reconnection logic to take over. []() |
| maintainPresenceState | boolean | Optional | `true` | Works only when [enableEventEngine](#enable-event-engine) is `true`. Whether the custom presence state information set using [pubnub.setState()](https://www.pubnub.com/docs/sdks/javascript/api-reference/presence#set-state) should be sent every time the SDK sends a subscribe call. |
| cryptoModule | PubNub.CryptoModule.legacyCryptoModule({ | Optional | `None` | The 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](#cryptomodule) section. |
| subscriptionWorkerUrl | string | Optional | `None` | The URL for the shared worker on the server or the origin as the page where it's used. For more information, refer to [Shared workers](#shared-workers). |
| cipherKey | string | Optional | `N/A` | This way of setting this parameter is deprecated, pass it to `cryptoModule` instead. If passed, will encrypt the payloads. |
| useRandomIVs | boolean | Optional | `true` | This 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. |
| uuid | string | Yes | `N/A` | This 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. |

:::warning 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` encrypts and decrypts messages and files. From 7.3.3 onward, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128-bit encryption and recommended 256-bit AES-CBC. For background, see [Message Encryption](https://www.pubnub.com/docs/general/setup/data-security#message-encryption) and [File Encryption](https://www.pubnub.com/docs/general/setup/data-security#file-encryption).

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.

For detailed encryption configuration, utility methods for encrypting/decrypting messages and files, and practical examples, see the dedicated [Encryption](https://www.pubnub.com/docs/sdks/javascript/api-reference/encryption) page.

:::note 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.
:::

#### Shared workers

Shared workers manage concurrent connections and presence across multiple client instances (tabs or windows). Source code:

```html
http://cdn.pubnub.com/sdk/javascript/pubnub.worker.11.0.1.js
```

Reasons to use shared workers:

* Browsers limit the number of parallel connections to the same origin (e.g., ps.pndsn.com) which may produce connection issues. Shared workers aggregate subscriptions for matching keysets, allowing them to use one long-poll subscribe request.
* When a long-poll subscribe request connection is closed, it can lead to false leave events if multiple tabs or windows are open. The shared worker tracks channels and groups to ensure long-poll requests are only terminated when all associated tabs or windows are closed.

:::note Hosting a shared worker
As browsers enforce the [Same-origin Policy](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy), you must host the shared worker under the same origin as the client application. Pages loaded from different origins won't be able to share a worker.
:::

##### Configuration

1. Download the shared worker source code from our CDN. http://cdn.pubnub.com/sdk/javascript/pubnub.worker.11.0.1.js
2. Host the shared worker on your server or make it available under the same origin as the page where it's used according to the Same-origin Policy.
3. Configure the subscriptionWorkerUrl property when initializing the PubNub client:

```javascript
const pubnub = new PubNub({
  subscribeKey: 'demo',
  publishKey: 'demo',
  userId: 'unique-user-id',
  // using PubNub JS SDK v9.6.0, make sure the versions match.
  // NOTE: 'subscriptionWorkerUrl' is only needed if you need to use SharedWorker.
  subscriptionWorkerUrl: 'https://www.my-domain.com/static/js/pubnub.worker.9.6.0.js',
});
```

When set, the client downloads the shared worker and uses it to manage subscriptions.

:::warning Worker version
The version of the shared worker must match the version of the PubNub client being used.
:::

### Sample code

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

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

:::note Required User ID
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.
:::

###### JavaScript

```javascript
// Initialize PubNub with your keys
const pubnubConfig = new PubNub({
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  publishKey: 'YOUR_PUBLISH_KEY',
  userId: 'YOUR_USER_ID',
  cryptoModule: PubNub.CryptoModule?.aesCbcCryptoModule({ cipherKey: 'YOUR_CIPHER_KEY' }),
  authKey: 'accessMangerToken',
  logLevel: PubNub.LogLevel.Debug,
  ssl: true,
  presenceTimeout: 130,
});
```

###### React

In React, initialize PubNub inside a `useEffect` hook and hold the instance in a `useRef` so it's stable across renders. Always destroy the client in the cleanup function to release connections when the component unmounts.

```jsx
import React, { useRef, useEffect } from 'react';
import PubNub from 'pubnub';

function App() {
  const pubnubRef = useRef(null);

  useEffect(() => {
    pubnubRef.current = new PubNub({
      publishKey: 'YOUR_PUBLISH_KEY',
      subscribeKey: 'YOUR_SUBSCRIBE_KEY',
      userId: 'YOUR_USER_ID',
    });

    return () => {
      if (pubnubRef.current) {
        pubnubRef.current.removeAllListeners();
        pubnubRef.current.destroy();
      }
    };
  }, []);

  return <div>Your app content</div>;
}
```

:::tip App-level PubNub instance
For apps where PubNub is used across many components, create the instance once outside the component tree (or use React Context) and pass it down as a prop, rather than initializing it inside each component.
:::

### Server operations

Servers can run multiple instances on the same machine and don’t use end‑user authentication. Initialize with `secretKey` to administer [Access Manager](https://www.pubnub.com/docs/general/security/access-control); this grants server‑side access to all channels and channel groups.

:::warning Access Manager module disabled in web builds
The pre-built web/browser bundle of the JavaScript SDK (including the CDN version) disables the Access Manager module and `secretKey` functionality at build time for security reasons. This means that in browser environments:
* Providing `secretKey` during initialization has no effect.
* Calling `grantToken()` will fail with "PAM module disabled".
* Requests will not include the `signature` parameter.
This is by design — exposing a `secretKey` in client-side browser code is a security risk. If you need to use Access Manager in a browser-based application, grant tokens from a **server-side** Node.js application and pass them to the client using [setToken()](https://www.pubnub.com/docs/sdks/javascript/api-reference/access-manager#set-token).
If you have a specific use case that requires Access Manager in a browser context (such as an internal admin tool), you can create a custom build of the SDK with the Access Manager module enabled. Refer to the [Bundling](#bundling) section and set the `PAM_MODULE` environment variable to `enabled` during the build.
:::

:::note 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.
:::

:::note Required User ID
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.
:::

```javascript
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:

:::note Required User ID
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.
:::

```javascript
// Initialize for Read Only Client

const pubnubReadOnly = 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.

:::note Required User ID
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.
:::

```javascript
const pubnubSSL = new PubNub({
  subscribeKey: 'mySubscribeKey',
  publishKey: 'myPublishKey',
  cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({ cipherKey: 'pubnubenigma' }),
  authKey: 'myAuthKey',
  logLevel: PubNub.LogLevel.Debug,
  userId: 'myUniqueUserId',
  ssl: true,
});
```

## Event listeners

PubNub SDKs provide several sources for real-time updates:

* The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users.
* The [Subscription](https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#create-a-subscription) object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
* The [SubscriptionsSet](https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#create-a-subscription-set) object can receive updates for all objects for which a list of subscription objects was created.

To work with these sources, the SDK provides local representations of server entities, so you can subscribe and add handlers per entity. For details, see [Publish & Subscribe](https://www.pubnub.com/docs/sdks/javascript/api-reference/publish-and-subscribe#event-listeners).

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

:::note Required User ID
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.
:::

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

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

```javascript
pubnub.setUserId(string)
```

| Parameter | Description |
| --- | --- |
| `userId` *Type: String | `userId` to set. |

```javascript
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.

```javascript
pubnub.getUserId();
```

:::note Required User ID 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

```javascript
pubnub.setAuthKey(string)
```

| Parameter | Description |
| --- | --- |
| `key` *Type: String | `Auth key` to set. |

### Sample code

```javascript
pubnub.setAuthKey('my_authkey');
```

### Returns

None.

## Filter expression

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) 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](https://www.pubnub.com/docs/general/messages/publish) documentation.

### Method(s)

```javascript
pubnub.setFilterExpression(
  filterExpression: string
)
```

| Parameter | Description |
| --- | --- |
| `filterExpression` *Type: string | PSV2 feature to `subscribe` with a custom filter expression. |

```javascript
pubnub.getFilterExpression()
```

This method doesn't take any arguments.

### Sample code

#### Set filter expression

```javascript
pubnub.setFilterExpression('such=wow');
```

#### Get filter expression

```javascript
pubnub.getFilterExpression();
```

## Terms in this document

* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.