JavaScript API & SDK Docs 12.0.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 guide walks you through 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 helps you get up and running with PubNub in your JavaScript application. The JavaScript software development kit (SDK) provides a simple interface for integrating PubNub real-time messaging. 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: For browser-based React applications using hooks and components
- 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 (
.jsextension):const PubNub = require('pubnub'); - For TypeScript files (
.tsextension):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 22 or later)
- For React: Node.js installed (version 22 or later) and a React project (e.g. created with Vite)
- 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)
JavaScript environment setup
For detailed guidance on Node.js versions, package managers (npm, yarn, pnpm, bun), TypeScript configuration, and modern build tools like Vite, refer to the JavaScript Environment Setup guide.
Setup
Get your PubNub keys
First, get your PubNub keys:
- Sign in or create an account on the PubNub Admin Portal
- Create an app (or use an existing one)
- Find your publish and subscribe keys in the app dashboard
When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve 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.
- Web
- Node.js
- React Native
- Source code
- React
To integrate PubNub into your web project, add the JavaScript SDK to your HTML page using the CDN:
1<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.12.0.0.js"></script>
You can also use the minified version for production:
1<script src="https://cdn.pubnub.com/sdk/javascript/pubnub.12.0.0.min.js"></script>
To integrate PubNub into your Node.js project, install the SDK using npm:
1npm install pubnub
Then import it in your project:
1const PubNub = require('pubnub');
For React Native projects, install the PubNub SDK:
1npm install pubnub
Then import it in your project:
1import PubNub from 'pubnub';
Clone the GitHub repository:
1git clone https://github.com/pubnub/javascript
Install the PubNub SDK using npm (or yarn/pnpm) in your React project:
1npm install pubnub
Then import it in your component or app entry point:
1import PubNub from 'pubnub';
If you don't have a React project yet, create one with Vite:
1npm create vite@latest my-pubnub-app -- --template react
2cd my-pubnub-app
3npm install
4npm install pubnub
Steps
Initialize PubNub
- Web
- Node.js
- React Native
- React
Create an instance of the PubNub class with your keys and a unique user ID:
1const pubnub = new PubNub({
2 publishKey: "demo",
3 subscribeKey: "demo",
4 userId: "web-user-" + Math.floor(Math.random() * 1000)
5});
Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.
Create an instance of the PubNub class with your keys and a unique user ID:
For more information, refer to the Configuration section of the SDK documentation.
Set up event listeners
Listeners help the application 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.
- Web
- Node.js
- React Native
- React
1// Add listener to handle messages, presence events, and connection status
2pubnub.addListener({
3 message: function(event) {
4 // Handle message event
5 console.log("New message:", event.message);
6 // Display message in the UI
7 displayMessage(event.message);
8 },
9 presence: function(event) {
10 // Handle presence event
11 console.log("Presence event:", event);
12 console.log("Action:", event.action); // join, leave, timeout
13 console.log("Channel:", event.channel);
14 console.log("Occupancy:", event.occupancy);
15 },
show all 44 lines2import PubNub from 'pubnub';
3
4function App() {
5 const pubnubRef = useRef(null);
6 const [messages, setMessages] = useState([]);
7 const [onlineCount, setOnlineCount] = useState(0);
8 const [isConnected, setIsConnected] = useState(false);
9
10 useEffect(() => {
11 pubnubRef.current = new PubNub({
12 publishKey: 'YOUR_PUBLISH_KEY',
13 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
14 userId: 'react-user-' + Math.floor(Math.random() * 1000),
15 });
show all 56 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:
- Web
- Node.js
- React Native
- React
1// Create a channel entity
2const channel = pubnub.channel('hello_world');
3
4// Create a subscription for this channel
5const subscription = channel.subscription();
6
7// Subscribe
8subscription.subscribe();
2import PubNub from 'pubnub';
3
4const pubnub = new PubNub({
5 publishKey: 'YOUR_PUBLISH_KEY',
6 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
7 userId: 'YOUR_USER_ID',
8});
9
10function App() {
11 useEffect(() => {
12 const channel = pubnub.channel('hello_world');
13 const subscription = channel.subscription({
14 receivePresenceEvents: true,
15 });
show all 25 lines
For more information, refer to the Subscribe section of the SDK documentation.
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 JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.
- Web
- Node.js
- React Native
- React
1// Function to publish a message
2async function publishMessage(text) {
3 if (!text.trim()) return;
4
5 try {
6 const result = await pubnub.publish({
7 message: {
8 text: text,
9 sender: pubnub.getUUID(),
10 time: new Date().toISOString()
11 },
12 channel: 'hello_world'
13 });
14 console.log("Message published with timetoken:", result.timetoken);
15 } catch (error) {
show all 25 lines2
3function MessageInput({ pubnub }) {
4 const [inputText, setInputText] = useState('');
5
6 const publishMessage = async () => {
7 if (!inputText.trim() || !pubnub) return;
8
9 try {
10 const result = await pubnub.publish({
11 message: {
12 text: inputText,
13 sender: pubnub.userId,
14 time: new Date().toISOString(),
15 },
show all 37 lines
Run the app
Once you've implemented all the previous steps (initialization, listeners, subscription, and publishing), you're ready to run your application:
- Web
- Node.js
- React Native
- React
- Save your HTML file with all the JavaScript code.
- Open the file in a web browser.
- Type a message in the input box and click Send.
- You should see your message appear in the messages area.
- To see real-time communication, open the same file in another browser tab.
-
Save your JavaScript file (e.g.,
index.js). -
Run the file using Node.js:
node index.js -
Type messages in the console and press Enter to send.
-
To see real-time communication, open another terminal window and run another instance of your app.
-
Start your React Native app:
npm run android
# or
npm run ios
# or
npm run web -
The app should launch on the selected platform.
-
Type a message in the input field and tap Send.
-
You should see your message appear in the messages list.
-
To see real-time communication, run the app on another device or simulator.
-
Start your Vite-based React app:
npm run dev -
Open http://localhost:5173 in your browser.
-
Type a message in the input field and click Send.
-
You should see your message appear in the messages list.
-
To see real-time communication, open the same URL in another browser tab.
Complete example
- Web
- Node.js
- React Native
- React
1<!DOCTYPE html>
2<html>
3<head>
4 <meta charset="utf-8" />
5 <title>PubNub Chat Example</title>
6 <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.12.0.0.js"></script>
7 <style>
8 #chat-container {
9 max-width: 600px;
10 margin: 0 auto;
11 padding: 20px;
12 font-family: Arial, sans-serif;
13 }
14 #messages {
15 height: 300px;
show all 134 lines3import PubNub from 'pubnub';
4
5const pubnub = new PubNub({
6 publishKey: 'YOUR_PUBLISH_KEY',
7 subscribeKey: 'YOUR_SUBSCRIBE_KEY',
8 userId: 'react-user-' + Math.floor(Math.random() * 1000),
9});
10
11export default function App() {
12 const [messages, setMessages] = useState([]);
13 const [inputText, setInputText] = useState('');
14 const [isConnected, setIsConnected] = useState(false);
15 const [onlineCount, setOnlineCount] = useState(0);
show all 121 lines