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.
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.
- Web
- Node.js
- TypeScript
- ReactNative
# your app is in index.html
touch index.html
# your app is in index.js
touch index.js
npm install --save-dev typescript @types/pubnub @types/node
# your app is in index.ts
touch index.ts
npm install -g expo-cli
# choose the template blank
expo init HelloPubNub
cd HelloPubNub
npm install PubNub
# your app is in App.js
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.
- Web
- Node.js
- TypeScript
- ReactNative
<!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 linesconst PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId",
});
// add listener
// publish message
// subscribe to a channel
// built-in package for reading from stdin
show all 32 linesconst PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId",
});
// add listener
// publish message
// subscribe to a channel
// built-in package for reading from stdin
show all 32 linesimport Pubnub from 'pubnub';
import { useState, useEffect } from "react"
import { TextInput, Button, Text, View } from 'react-native';
const pubnub = new Pubnub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId"
});
export default function App() {
const [messages, setMessages] = useState([]);
const [text, onChangeText] = useState([]);
useEffect(() => {
show all 52 linesFor 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:
- Web
- Node.js
- TypeScript
- ReactNative
<!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 linesconst PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId",
});
// create a local channel entity
const channel = pubnub.channel('hello_world');
// create a subscription on the channel
const subscription = channel.subscription();
// add general listener
pubnub.addListener({
show all 57 linesimport PubNub from 'pubnub';
import { createInterface } from 'readline';
// Assuming detailed type definitions are not available for the newer API, we use a more generic approach.
// If available, update types accordingly based on the new SDK documentation.
interface IMessageEvent {
message: {
title: string;
description: string;
}
}
const pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
show all 67 linesimport Pubnub from 'pubnub';
import { useState, useEffect } from "react";
import { TextInput, Button, Text, View } from 'react-native';
const pubnub = new Pubnub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId"
});
export default function App() {
const [messages, setMessages] = useState([]);
const [text, onChangeText] = useState("");
useEffect(() => {
show all 62 linesNow, run your app to see if you did everything correctly:
- Web
- Node.js
- TypeScript
- ReactNative
- Save
index.html
and open it in a web browser. - Type a message into the input and click Send. You should see the message appear.
- Open the file in another tab and send messages between the two instances!
node index.js
- You should see
Connected
printed to the terminal. - Type a message into the terminal and press Return. You should see the message appear.
- Open another terminal window and send messages between the two instances!
npx tsc index.ts
node index.js
- You should see
Connected
printed to the terminal. - Type a message into the terminal and hit Return. You should see the message appear.
- Open another terminal window and send messages between the two instances!
expo start
- Follow directions from the CLI to open the app on one of your devices.
- Type a message into the input and hit Send. You should see the message appear.
- If you have multiple devices, try opening the app on another 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
andmessage
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.