---
source_url: https://www.pubnub.com/docs/sdks/javascript/quickstart-web
title: "Quickstart: PubNub JavaScript SDK in the browser"
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 a web page. Install from the CDN, subscribe to a channel, publish, and see the message arrive.
---

# Quickstart: PubNub JavaScript SDK in the browser

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" web page that connects to PubNub, subscribes to a channel, and publishes a message that arrives in the same page. You need one HTML file and a browser.

Building for Node.js, 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 a modern web browser and a PubNub account.

### 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 web project, add the JavaScript SDK to your HTML page using the CDN:

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

You can also use the minified version for production by changing the file name to `pubnub.13.1.3.min.js`.

:::tip Using a bundler?
If your project uses a bundler such as Vite or webpack, install the `pubnub` package from npm instead. For package managers and TypeScript, refer to [Set up your JavaScript environment](https://www.pubnub.com/docs/sdks/javascript/set-up-your-environment.md).
:::

## 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 adds each incoming message to the list on the page and logs when the client connects.

```javascript
pubnub.addListener({
  message: (event) => {
    // Add every incoming message to the list on the page
    const item = document.createElement('li');
    item.textContent = `${event.publisher}: ${event.message}`;
    document.querySelector('ul')?.append(item);
  },
  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
const subscription = pubnub.channel('hello_world').subscription();
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 the text from the input box when you click **Send**.

```javascript
document.querySelector('button')?.addEventListener('click', async () => {
  const input = document.querySelector('input');
  if (!input || !input.value.trim()) return;

  try {
    const result = await pubnub.publish({
      channel: 'hello_world',
      message: input.value,
    });
    console.log(`Published, timetoken: ${result.timetoken}`);
    input.value = '';
  } 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 page below combines the CDN script tag and all the code from the previous steps. Save it as `index.html`, replace the three placeholders, and open the file in your browser.

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>PubNub quickstart</title>
  <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.13.1.3.js"></script>
</head>
<body>
  <h1>PubNub quickstart</h1>
  <ul></ul>
  <input placeholder="Type a message" />
  <button>Send</button>

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

    pubnub.addListener({
      message: (event) => {
        // Add every incoming message to the list on the page
        const item = document.createElement('li');
        item.textContent = `${event.publisher}: ${event.message}`;
        document.querySelector('ul')?.append(item);
      },
      status: (event) => {
        if (event.category === 'PNConnectedCategory') {
          console.log('Connected to PubNub');
        }
      },
    });

    const subscription = pubnub.channel('hello_world').subscription();
    subscription.subscribe();

    document.querySelector('button')?.addEventListener('click', async () => {
      const input = document.querySelector('input');
      if (!input || !input.value.trim()) return;

      try {
        const result = await pubnub.publish({
          channel: 'hello_world',
          message: input.value,
        });
        console.log(`Published, timetoken: ${result.timetoken}`);
        input.value = '';
      } catch (error) {
        console.error(`Publish failed: ${error}`);
      }
    });
  </script>
</body>
</html>
```

Verify that it works:

1. Open the browser console. You should see `Connected to PubNub`.
2. Type `Hello, world!` in the input box and click **Send**.
3. The message appears in the list on the page as `YOUR_USER_ID: Hello, world!`, and the console logs the timetoken of the published message.
4. To see real-time communication between two clients, open the same file in a second browser tab, and send a message from either tab. It appears in both lists.

If the message does not arrive, refer to [Troubleshooting](https://www.pubnub.com/docs/sdks/javascript/troubleshooting.md). If the console shows 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
