---
source_url: https://www.pubnub.com/docs/sdks/javascript/quickstart-node
title: "Quickstart: PubNub JavaScript SDK in Node.js"
updated_at: 2026-11-09T13:29:01.000Z
sdk_name: PubNub JavaScript SDK
sdk_version: 13.1.3
description: Send your first message with the PubNub JavaScript SDK in Node.js. Install with npm, subscribe to a channel, publish, and see the message arrive in your terminal.
---

# Quickstart: PubNub JavaScript SDK in Node.js

PubNub JavaScript SDK, use the latest version: 13.1.3

Install:

```bash
npm install pubnub@13.1.3
```

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

This quickstart walks you through a "Hello, World" Node.js script that connects to PubNub, subscribes to a channel, and publishes a message that arrives in the same process. You need one file and a terminal.

Building for the browser, React, or React Native instead? Refer to [Choose your runtime](https://www.pubnub.com/docs/sdks/javascript/choose-runtime.md).

## Before you begin

You need [Node.js](https://nodejs.org/) installed (version 22 or later) and a PubNub account. For package managers and TypeScript, refer to [Set up your JavaScript environment](https://www.pubnub.com/docs/sdks/javascript/set-up-your-environment.md).

### Get your PubNub keys

First, get your PubNub keys:

* [Sign in](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) on the PubNub Admin Portal
* Create an app (or use an existing one)
* Find your publish and subscribe keys in the app dashboard

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

## Install

:::note SDK version
Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.
:::

To integrate PubNub into your Node.js project, create a project folder and install the SDK using npm:

```bash
mkdir pubnub-quickstart
cd pubnub-quickstart
npm install pubnub
```

This quickstart uses an ES module, so you save the code in a file named `index.mjs`. That lets you use `import` and top-level `await`. If your project uses CommonJS, import the SDK with `const PubNub = require('pubnub');` instead.

```javascript
import PubNub from 'pubnub';
```

## Initialize

Create an instance of the PubNub class with your keys and a unique user ID. Replace the placeholders with the publish and subscribe keys from the Admin Portal.

```javascript
const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});
```

Always set the `userId` to uniquely identify the user or device that connects to PubNub. Keep it 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.

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration.md) section of the SDK documentation.

## Subscribe

Listeners help the application react to events and messages. This listener prints each incoming message and logs when the client connects.

```javascript
pubnub.addListener({
  message: (event) => {
    console.log(`Received on ${event.channel}: ${event.message}`);
  },
  status: (event) => {
    if (event.category === 'PNConnectedCategory') {
      console.log('Connected to PubNub');
    }
  },
});
```

To receive messages on a channel, you need to subscribe to it. PubNub offers an entity-based subscription approach that gives you more control and flexibility.

```javascript
// Create a channel entity
const channel = pubnub.channel('hello_world');

// Create a subscription
const subscription = channel.subscription({
  receivePresenceEvents: true, // to receive presence events
});

// Subscribe
subscription.subscribe();
```

For complete details on subscribing and handling events, refer to the [Subscribe](https://www.pubnub.com/docs/sdks/javascript/api-reference/subscribe.md#subscribe) section of the SDK documentation.

## Publish

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. A message can be any JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

This code publishes once the client is connected, so the subscription is already active and your own listener receives the message. It adds a second status listener that runs when the client reports `PNConnectedCategory`.

```javascript
pubnub.addListener({
  status: async (event) => {
    if (event.category !== 'PNConnectedCategory') return;
    try {
      const result = await pubnub.publish({
        channel: 'hello_world',
        message: 'Hello, world!',
      });
      console.log(`Published, timetoken: ${result.timetoken}`);
    } catch (error) {
      console.error(`Publish failed: ${error}`);
    }
  },
});
```

For more information, refer to the [Publish](https://www.pubnub.com/docs/sdks/javascript/api-reference/publish.md#publish) section of the SDK documentation.

## Run

The file below combines all the code from the previous steps. Save it as `index.mjs` in your project folder and replace the three placeholders.

```javascript
import PubNub from 'pubnub';

const pubnub = new PubNub({
  publishKey: 'YOUR_PUBLISH_KEY',
  subscribeKey: 'YOUR_SUBSCRIBE_KEY',
  userId: 'YOUR_USER_ID',
});

pubnub.addListener({
  message: (event) => {
    console.log(`Received on ${event.channel}: ${event.message}`);
  },
  status: (event) => {
    if (event.category === 'PNConnectedCategory') {
      console.log('Connected to PubNub');
    }
  },
});

// Create a channel entity
const channel = pubnub.channel('hello_world');

// Create a subscription
const subscription = channel.subscription({
  receivePresenceEvents: true, // to receive presence events
});

// Subscribe
subscription.subscribe();

pubnub.addListener({
  status: async (event) => {
    if (event.category !== 'PNConnectedCategory') return;
    try {
      const result = await pubnub.publish({
        channel: 'hello_world',
        message: 'Hello, world!',
      });
      console.log(`Published, timetoken: ${result.timetoken}`);
    } catch (error) {
      console.error(`Publish failed: ${error}`);
    }
  },
});
```

Run it with Node.js:

```bash
node index.mjs
```

Verify that it works. The terminal prints these lines, and their order can vary:

```text
Connected to PubNub
Published, timetoken: <a 17-digit timetoken>
Received on hello_world: Hello, world!
```

The script keeps running because the subscription stays open. Press **Ctrl+C** to stop it. To see real-time communication between two clients, run the script in a second terminal while the first one is still running. The first terminal prints another `Received on hello_world: Hello, world!` line.

If the message does not arrive, refer to [Troubleshooting](https://www.pubnub.com/docs/sdks/javascript/troubleshooting.md). If you see a 403 (Access Denied) error, your keyset may have Access Manager enabled. Verify that your token has read permissions for the subscribed channel. Refer to [Configure access control](https://www.pubnub.com/docs/security/access-control/configure-access-control.md).

## Next steps

You created your first PubNub JavaScript application. Here is what to explore next:

* Build a feature with the [how-tos](https://www.pubnub.com/docs/sdks/javascript.md), such as showing who is online or loading message history.
* Learn about the [JavaScript Chat SDK](https://www.pubnub.com/docs/chat/chat-sdk.md) for ready-to-use chat features such as typing indicators and read receipts.
* Try out [Presence](https://www.pubnub.com/docs/sdks/javascript/api-reference/presence.md) to track online and offline status.
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/javascript/api-reference/message-persistence.md) to store and retrieve messages.
* Use [Access Manager](https://www.pubnub.com/docs/sdks/javascript/api-reference/access-manager.md) to secure your channels.
* Explore [Channel Groups](https://www.pubnub.com/docs/sdks/javascript/api-reference/channel-groups.md) to organize your channels.
* Explore the [GitHub repository](https://github.com/pubnub/javascript) for more code samples.
* Follow a tutorial: [IoT dashboard](https://www.pubnub.com/tutorials/iot-dashboard-tutorial-javascript/), [Geolocation app](https://www.pubnub.com/tutorials/geolocation-tracking-tutorial-javascript/), or [Delivery app](https://www.pubnub.com/tutorials/geolocation-tracker/).
* Check the [SDK reference documentation](https://www.pubnub.com/docs/sdks/javascript/api-reference/configuration.md) for detailed API information.
* Visit the [support portal](https://support.pubnub.com/) or ask the AI assistant (the looking glass icon at the top of the page).

Last updated at: 2026-11-09T13:29:01.000Z
