JavaScript API & SDK Docs 9.6.0

Chat SDK

If you want to create a chat app, you can use our Chat SDK, which relies on the JavaScript SDK, is written in TypeScript, and offers a set of chat-specific methods to manage users, channels, messages, typing indicators, quotes, mentions, threads, and many more.

In this guide, we'll create a simple "Hello, World" application that demonstrates the core concepts of PubNub:

  • Setting up a connection
  • Sending messages
  • Receiving messages in real-time

Overview

This guide will help you get up and running with PubNub in your JavaScript application. Since JavaScript is commonly used across different platforms, we provide platform-specific guidance for:

  • Web: For developers building browser-based applications
  • Node.js: For server-side applications
  • React Native: For mobile app development

The core PubNub concepts and API usage remain the same across all platforms, but implementation details like lifecycle management and UI updates differ. Select the appropriate tab in each section to see platform-specific guidance.

You can use either JavaScript or TypeScript with any of these platforms. The only difference is in how you import PubNub:

  • For JavaScript files (.js extension): const PubNub = require('pubnub');
  • For TypeScript files (.ts extension): import PubNub from 'pubnub';

JavaScript SDK supports a wide variety of environments including browsers, Node.js, React Native, React, Angular, Vue, and other JavaScript frameworks.

Prerequisites

Before we dive in, make sure you have:

  • A basic understanding of JavaScript
  • For browser applications: A modern web browser
  • For Node.js: Node.js installed (version 10 or later)
  • For React Native: React Native development environment set up
  • A PubNub account (we'll help you set this up!)
  • (Optional) If you want to use TypeScript: TypeScript installed (version 4.0 or later)

Setup

Get your PubNub keys

First things first – you'll need your PubNub keys to get started. Here's how to get them:

  • Sign in or create an account on the PubNub Admin Portal
  • Create a new app (or use an existing one)
  • Find your publish and subscribe keys in the app's dashboard

When you create a new app, PubNub automatically generates your first set of keys. While you can use the same keys for development and production, we recommend creating separate keysets for each environment for better security and management.

Install the SDK

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:

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

You can also use the minified version for production:

<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.9.6.0.min.js"></script>

You can also download the source code from GitHub and build it yourself.

Steps

Initialize PubNub

Create an instance of the PubNub class with your keys and a unique user ID:

const pubnub = new PubNub({
publishKey: "demo",
subscribeKey: "demo",
userId: "web-user-" + Math.floor(Math.random() * 1000)
});

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

For more information, refer to the Configuration section of the SDK documentation.

Set up event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

For complete details on subscribing and handling events, refer to the Publish and Subscribe API Reference.

// Add listener to handle messages, presence events, and connection status
pubnub.addListener({
message: function(event) {
// Handle message event
console.log("New message:", event.message);
// Display message in the UI
displayMessage(event.message);
},
presence: function(event) {
// Handle presence event
console.log("Presence event:", event);
console.log("Action:", event.action); // join, leave, timeout
console.log("Channel:", event.channel);
console.log("Occupancy:", event.occupancy);
},
show all 44 lines

Create a subscription

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

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

// Create a subscription for this channel
const subscription = channel.subscription();

// Subscribe
subscription.subscribe();

Publish messages

Once you've set up your subscription, you can start publishing messages to channels.

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 type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

// Function to publish a message
async function publishMessage(text) {
if (!text.trim()) return;

try {
const result = await pubnub.publish({
message: {
text: text,
sender: pubnub.getUUID(),
time: new Date().toISOString()
},
channel: 'hello_world'
});
console.log("Message published with timetoken:", result.timetoken);
} catch (error) {
show all 25 lines

Run the app

Once you've implemented all the previous steps (initialization, listeners, subscription, and publishing), you're ready to run your application:

  1. Save your HTML file with all the JavaScript code.
  2. Open the file in a web browser.
  3. Type a message in the input box and click Send.
  4. You should see your message appear in the messages area.
  5. To see real-time communication, open the same file in another browser tab.

Complete example

Below are complete working examples for each platform that combine all the previous steps into a single, functional application:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PubNub Chat Example</title>
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.9.6.0.js"></script>
<style>
#chat-container {
max-width: 600px;
margin: 0 auto;
padding: 20px;
font-family: Arial, sans-serif;
}
#messages {
height: 300px;
show all 134 lines

The examples above showcase complete working code that integrates all the concepts covered in this guide:

  • PubNub initialization with proper configuration
  • Event listener setup for messages and connection status
  • Channel subscription using the entity-based approach
  • Message publishing with error handling
  • User interface components (where applicable)
  • Cleanup and resource management

Next steps

Great job! 🎉 You've successfully created your first PubNub JavaScript application. Here are some exciting things you can explore next:

  • Learn about the JavaScript Chat SDK for ready-to-use chat features.
  • Implement user Presence to show who's online.
  • Add typing indicators and read receipts.
Last updated on