PubNub JavaScript SDK 7.4.5

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

React SDK

The JavaScript SDK can be used with React and React Native. We also provide a dedicated React SDK for React and React Native.

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.7.4.5.js
https://cdn.pubnub.com/sdk/javascript/pubnub.7.4.5.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.7.4.5.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.

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 make your app display messages as they are received.

// paste below "add listener" comment
const listener = {
status: (statusEvent) => {
if (statusEvent.category === "PNConnectedCategory") {
console.log("Connected");
}
},
message: (messageEvent) => {
showMessage(messageEvent.message.description);
},
presence: (presenceEvent) => {
// handle presence
}
};
pubnub.addListener(listener);

For more information, refer to the Listeners 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 subscribed to that channel.

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 receive messages from the app, subscribe to the channel.

// paste below "subscribe to a channel" comment
pubnub.subscribe({
channels: ["hello_world"]
});

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

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.7.4.5.js"></script>
</head>
<body>
<script>
const buttonClick = () => {
var input = document.getElementById('message-body');
publishMessage(input.value);
input.value = '';
};
show all 80 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
  • adds the status, message, and presence event listeners
  • subscribes to a channel
  • publishes a message

Configuring PubNub

The following code is the minimum configuration you need 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"
});

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 three listeners to the app: message, presence, and status. The message listener listens for incoming messages on a particular channel. When it receives a message, the app displays the message.

The presence listener reacts to events connected to presence. In this example, it is a no operation listener.

In this example, the status listener prints "Connected" to the console.

const listener = {
status: (statusEvent) => {
if (statusEvent.category === "PNConnectedCategory") {
console.log("Connected");
}
},
message: (messageEvent) => {
showMessage(messageEvent.message.description);
},
presence: (presenceEvent) => {
// handle presence
}
};
pubnub.addListener(listener);

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

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 subscribed to that channel. In this example, you subscribe to a channel named hello_world.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, and strings) that is 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);
}

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

pubnub.subscribe({
channels: ["hello_world"]
});

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

Next steps

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

Last updated on