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.
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.
- 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.7.4.5.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.
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:
- 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.7.4.5.js"></script>
</head>
<body>
<script>
const buttonClick = () => {
var input = document.getElementById('message-body');
publishMessage(input.value);
input.value = '';
};
show all 80 linesconst PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId",
});
// add listener
const listener = {
status: (statusEvent) => {
if (statusEvent.category === "PNConnectedCategory") {
console.log("Connected");
}
},
show all 58 linesconst PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey: "myPublishKey",
subscribeKey: "mySubscribeKey",
userId: "myUniqueUserId",
});
// add listener
const listener = {
status: (statusEvent) => {
if (statusEvent.category === "PNConnectedCategory") {
console.log("Connected");
}
},
show all 58 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 79 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
- adds the
status
,message
, andpresence
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.