PubNub JavaScript SDK 8.3.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.

This page outlines the steps to follow to create a simple Hello, World application with PubNub. This covers the basics of integrating PubNub in your application: setting up a connection to PubNub, and sending and receiving messages.

  1. PubNub account
  2. Download the SDK
  3. Send messages

PubNub account

Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the SDK

Download the SDK from any of the following sources:

Use a CDN

To integrate PubNub into your project using a content delivery network:

https://cdn.pubnub.com/sdk/javascript/pubnub.8.3.0.js
https://cdn.pubnub.com/sdk/javascript/pubnub.8.3.0.min.js

Use a package manager

To integrate PubNub into your Node.js, TypeScript, React Native, or web project with npm:

npm install pubnub

Get the source code

https://github.com/pubnub/javascript

Project Setup

Platforms

These examples use TypeScript with Node.js, but you can combine TypeScript with any of the other platforms.

Create the file for your app and install additional dependencies.

# your app is in index.html
touch index.html

Configure PubNub

Add the following code to the file for your app. This is the minimum configuration you need to send and receive messages with PubNub.

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Hello, PubNub</title>
<!-- Update this block with the URL to the content delivery network version of the SDK -->
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.8.3.0.js"></script>
</head>
<body>
<script>
const buttonClick = () => {
var input = document.getElementById('message-body');
publishMessage(input.value);
input.value = '';
};
show all 50 lines

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

Publish and subscribe

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who subscribes.

Copy the code below to publish a message when publishMessage() is called.

// paste below "publish message" comment
const publishMessage = async (message) => {
// With the right payload, you can publish a message, add a reaction to a message,
// send a push notification, or send a small payload called a signal.
const publishPayload = {
channel : "hello_world",
message: {
title: "greeting",
description: message
}
};
await pubnub.publish(publishPayload);
}

To subscribe to real-time updates, you must create a subscription or a subscription set and send a subscribe() call.

It is best to define the subscription before you introduce the listeners and then send the subscribe() call, so place the relevant code in the appropriate places within your app.

// create a local channel entity
const channel = pubnub.channel('hello_world');
// create a subscription on the channel
const subscription = channel.subscription();
// add listeners (next step)
...
// subscribe to the channel
subscription.subscribe();

For more information, refer to the Publish and Subscribe section of the SDK documentation and to Publishing a Message.

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

Add the following code to log the subscription connection status and make your app display messages as they are received.

// add a status listener on the pubnub client
pubnub.addListener({
status: (s) => {
console.log('Status', s.category);
},
});

// add an onMessage listener to the channel subscription
subscription.onMessage = (messageEvent) => {
showMessage(messageEvent.message.description);
};

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

Putting it all together

Your code should now look similar to the one below:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Hello, PubNub</title>
<!-- Update this block with the URL to the content delivery network version of the SDK -->
<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.8.3.0.js"></script>
</head>
<body>
<script>
const buttonClick = () => {
var input = document.getElementById('message-body');
publishMessage(input.value);
input.value = '';
};
show all 77 lines

Now, run your app to see if you did everything correctly:

  1. Save index.html and open it in a web browser.
  2. Type a message into the input and click Send. You should see the message appear.
  3. Open the file in another tab and send messages between the two instances!

Congratulations! You've just subscribed to a channel and sent your first messages.

Walkthrough

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things with PubNub:

  • configures a PubNub connection
  • creates a subscription using a local channel entity
  • adds the status and message event listeners
  • subscribes to a channel
  • publishes a message

Configuring PubNub

The following code is the minimum configuration to send and receive messages with PubNub. For more information, refer to the Configuration section of the SDK documentation.

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

Publishing and subscribing

PubNub uses the Publish/Subscribe model for real-time communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to send to one or more recipients

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who subscribes. In this example, you subscribe to a channel named hello_world.

You can subscribe to more than one channel with a single subscribe call, but in this example, you subscribe to a single channel:

// create a local channel entity
const channel = pubnub.channel("hello_world");
// create a subscription on the channel
const subscription = channel.subscription();
// add listeners
...
// subscribe to the channel
subscription.subscribe();

A message can be any JSON-serializable data (such as objects, arrays, integers, and strings) smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms, regardless of their location.

In the example app, you define the message and the channel you're going to send the message to in the publishPayload variable within the publishMessage() function declaration:

const publishMessage = async (message) => {
// With the right payload, you can publish a message, add a reaction to a message,
// send a push notification, or send a small payload called a signal.
const publishPayload = {
channel : "hello_world",
message: {
title: "greeting",
description: message
}
};
await pubnub.publish(publishPayload);
}

For more information, refer to the Publish and Subscribe section of the SDK documentation and to Publishing a Message.

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

You added two listeners to the app: message and status. The message listener listens for incoming messages on a particular channel. When it receives a message, the app displays the message.

You can register the same listener for different subscriptions. Even though they listen for the same event, they can behave entirely differently.

// add a status listener on the pubnub client
pubnub.addListener({
status: (s) => {
console.log('Status', s.category);
},
});

// add an onMessage listener to the channel subscription
subscription.onMessage = (messageEvent) => {
showMessage(messageEvent.message.description);
};

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

Next steps

You have just learned how to use the JavaScript SDK to send and receive messages using PubNub. Next, look at the SDK's reference documentation covering PubNub API in more detail.

Last updated on