Set up your JavaScript environment
This guide sets up a development environment for the PubNub JavaScript SDK (the pubnub package) and installs it. Do the sections that match your runtime and skip the rest. To pick a runtime first, refer to Choose your runtime.
Install the SDK
Install the pubnub package with the package manager your project uses:
# npm (bundled with Node.js)
npm install pubnub
# yarn
yarn add pubnub
# pnpm
pnpm add pubnub
# bun
bun add pubnub
Each package manager writes its own lockfile: package-lock.json, yarn.lock, pnpm-lock.yaml, or bun.lockb. Commit the lockfile so installs stay the same across environments.
To build the SDK yourself, clone the GitHub repository:
1git clone https://github.com/pubnub/javascript
Set up TypeScript
If you write TypeScript, you do not need an additional @types package, because the PubNub JavaScript SDK includes its type definitions.
-
Install TypeScript as a dev dependency:
npm install --save-dev typescript -
Create a
tsconfig.jsonfile:npx tsc --init -
Import PubNub with types:
For PubNub projects, use these tsconfig.json settings:
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Choose a module format
The PubNub JavaScript SDK supports both ES Modules (ESM) and CommonJS imports.
If your project uses ES Modules, import the SDK with import. The pubnub package works with ESM through Node.js interop and bundlers such as Vite, webpack, and esbuild:
1
If your project uses CommonJS, import the SDK with require:
const PubNub = require('pubnub');
To use ES Modules in Node.js, do one of the following:
- Use the
.mjsfile extension. - Add
"type": "module"to yourpackage.json. - Use a bundler such as Vite or esbuild.
Load the SDK from a CDN
If your browser application has no bundler, load the PubNub JavaScript SDK from the PubNub content delivery network (CDN):
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.13.1.3.js"></script>
Pin the script to a specific version, such as pubnub.13.1.3.js, instead of latest. A pinned version cannot introduce breaking changes without you choosing to upgrade.
Share subscriptions across browser tabs
Run a shared worker to manage subscriptions and presence for several PubNub JavaScript SDK clients in different browser tabs or windows. Shared workers work in browsers only. Use one if several tabs of your app reach the browser limit on parallel connections to one origin, for example ps.pndsn.com, or if closing a tab produces false leave events.
-
Download the worker from the CDN. Its version must match the version of the PubNub client:
https://cdn.pubnub.com/sdk/javascript/pubnub.worker.13.1.3.js -
Host the worker on your server under the same origin as the page that uses it. Browsers enforce the Same-origin Policy, so pages loaded from other origins cannot share a worker.
-
Set
subscriptionWorkerUrlto the URL of the hosted worker. The client downloads the worker and uses it to manage subscriptions:1
The worker aggregates subscriptions for matching keysets into one long-poll subscribe request. It tracks channels and channel groups and ends the request only when all associated tabs are closed.
Build a custom bundle
The PubNub JavaScript SDK builds with Rollup or Webpack, and environment variables decide which modules the bundle contains. Setting a variable to disabled removes that module through tree-shaking.
| Variable | Module | Default |
|---|---|---|
CRYPTO_MODULE | Cryptors, including Concise Binary Object Representation (CBOR) support | enabled |
SHARED_WORKER | Browser background subscription requests | enabled |
PUBLISH_MODULE | Messages and signals | enabled |
SUBSCRIBE_MODULE | Real-time updates and their handling | enabled |
SUBSCRIBE_EVENT_ENGINE_MODULE | Subscribe with the standardized workflows (enableEventEngine: true) | enabled |
SUBSCRIBE_MANAGER_MODULE | Subscribe with the legacy subscription manager (enableEventEngine: false) | enabled |
PRESENCE_MODULE | Presence and user state | enabled |
PAM_MODULE | Access Manager token and authKey permissions | disabled |
CHANNEL_GROUPS_MODULE | Channel groups | enabled |
MESSAGE_PERSISTENCE_MODULE | Message Persistence access and message removal | enabled |
MOBILE_PUSH_MODULE | Mobile push notifications for channels | enabled |
APP_CONTEXT_MODULE | App Context entities and relationships | enabled |
DATA_SYNC_MODULE | DataSync entities, relationships, and typed resources | enabled |
FILE_SHARING_MODULE | File sharing | enabled |
MESSAGE_REACTIONS_MODULE | Message reactions (message actions) | enabled |
The Rollup configuration disables PAM_MODULE by default, which is why browser builds lack Access Manager support. To keep Access Manager in a custom bundle, set PAM_MODULE=enabled. That bundle exposes the Access Manager code in the browser, so build it only for cases such as an internal admin tool.
Use the SDK's rollup.config.js as a starting point.
- Rollup
- Webpack
-
Clone the PubNub JavaScript SDK repository.
-
In
rollup.config.js, setenableTreeShakingtotrue. -
Disable the modules you do not need, for example:
export PRESENCE_MODULE=disabled PUBLISH_MODULE=disabled -
Run
rollup -c rollup.config.js --bundleConfigAsCjs. The bundle is in theuploaddirectory of your clone.
-
Clone the PubNub JavaScript SDK repository.
-
Create
webpack.config.jsbased on the Rollup configuration. Define each module variable from the table withDefinePlugin, for example:const webpack = require('webpack');
module.exports = {
// Other configuration...
plugins: [
new webpack.DefinePlugin({
'process.env.PRESENCE_MODULE': JSON.stringify(process.env.PRESENCE_MODULE ?? 'enabled'),
'process.env.PUBLISH_MODULE': JSON.stringify(process.env.PUBLISH_MODULE ?? 'enabled'),
// One entry for every variable in the table.
}),
],
}; -
Disable the modules you do not need:
export PRESENCE_MODULE=disabled PUBLISH_MODULE=disabled -
Run
npx webpack --config webpack.config.js. The bundle is in the output directory you configured. For other settings, see the Webpack documentation.
Set up React Native
In a React Native project, install the SDK together with react-native-url-polyfill:
npm install pubnub react-native-url-polyfill
As of SDK v12.0.0, the SDK no longer bundles react-native-url-polyfill, so you must install it explicitly. After you install it, the SDK applies the polyfill automatically and needs no additional import or setup step.
Next steps
- Configuration API. Set
subscriptionWorkerUrland the other client settings. - Quickstart: Web. Send your first message in the browser.
- Quickstart: Node.js. Send your first message from a server.
- Quickstart: React. Send your first message from a React application.
- Quickstart: React Native. Send your first message from a mobile application.