Quickstart

Showing JavaScript examples.

In this quickstart, you publish a message to a PubNub channel and receive it in the same program. That's your first end-to-end real-time exchange with PubNub. Pick your language above. Every step and code sample on this page follows it.

Before you begin​

Make sure you have a PubNub account and your own keyset. A keyset is the set of publish, subscribe, and secret keys that identifies your application to the PubNub network.

If you don't have one yet, the fastest way to get one is using a Prototype:

  1. Sign up or log in to Admin Portal.
  2. In the Recent prototypes section, click the app. A new app is created automatically when you log in for the first time.
  3. Copy the publish key and subscribe keys.
Create a keyset manually

You can also follow Set up your account to create one, then come back here.

Set up the project​

Make sure you have Node.js 22 or later installed, then create a new directory and install the PubNub JavaScript SDK:

mkdir pubnub-quickstart
cd pubnub-quickstart
npm init -y
npm install pubnub

Then create a file called index.js in that directory.

Initialize PubNub​

Open index.js and add the following:

const PubNub = require('pubnub');

const pubnub = new PubNub({
publishKey: 'YOUR_PUBLISH_KEY',
subscribeKey: 'YOUR_SUBSCRIBE_KEY',
userId: 'quickstart-user',
});

Replace YOUR_PUBLISH_KEY and YOUR_SUBSCRIBE_KEY with the keys from your keyset, wherever this tutorial shows them. The userId is a string that identifies this client on the PubNub network. Use any unique value for now.

Subscribe to a channel​

Append this to index.js:

const channel = pubnub.channel('quickstart-channel');
const subscription = channel.subscription();

subscription.onMessage = (event) => {
console.log('Message received:', event.message.text);
};

pubnub.addListener({
status: (event) => {
if (event.category === 'PNConnectedCategory') {
publishMessage();
}
},
});

show all 16 lines

pubnub.channel() creates a channel entity, and .subscription() scopes a subscription to it. subscription.onMessage fires each time a message arrives on that channel. For more on entities and subscriptions, refer to Pub/Sub overview.

pubnub.addListener() reports connection status at the client level. When status reports PNConnectedCategory, the listener calls publishMessage(), which you add in the next step. That way the message publishes only once the subscription is confirmed active.

Channels are created implicitly the first time they are used and do not require provisioning, so quickstart-channel becomes available the moment you use it.

Publish a message​

Append this to index.js:

async function publishMessage() {
try {
await pubnub.publish({
channel: 'quickstart-channel',
message: { text: 'Hello, PubNub!' },
});
} catch (error) {
console.error('Publish failed:', error);
}
}

publish() sends a message to a channel. The message can be any JSON-serializable value. Here it's a plain object with a text field.

Run the program​

node index.js

You should see:

Message received: Hello, PubNub!

The program keeps running because the subscription holds the connection open. Press Ctrl+C to stop it.

The message travels from your program to the PubNub network and back to the same subscriber.

Troubleshooting​

If the output does not appear:

  • Verify your keys. Publish keys start with pub-c- and subscribe keys start with sub-c-. Swapping them is a common mistake.
  • Check for Access Manager errors. If Access Manager is enabled on your keyset, the SDK requires a valid token to subscribe and publish. If your status handler reports an access-denied status, disable Access Manager on your keyset in the Admin Portal or refer to Access Manager.
  • Check your network. If the SDK cannot reach PubNub, your status handler reports a connection failure instead of a connected status, so the publish step never runs. Verify that the machine has internet access and that outbound HTTPS to *.pubnub.com, *.pndsn.com, *.pubnub.net, and *.pubnubapi.com isn't blocked by a firewall. If your network policy requires IP allowlisting instead of domain allowlisting, that requires a paid plan. Contact support for the current IP list.

What happened​

Your program acted as both publisher and subscriber on quickstart-channel:

  1. You created a subscription to quickstart-channel and attached a handler for incoming messages.
  2. You activated the subscription, which opened a connection to PubNub and started listening.
  3. Once the subscription was active, your program published a message to the same channel.
  4. PubNub routed the message to every active subscriber on quickstart-channel, including this program.
  5. Your message handler ran and printed the text.

This is the pub/sub model in practice: publishers send messages to a channel, and PubNub delivers them to all current subscribers.

Complete file​

const PubNub = require('pubnub');

const pubnub = new PubNub({
publishKey: 'YOUR_PUBLISH_KEY',
subscribeKey: 'YOUR_SUBSCRIBE_KEY',
userId: 'quickstart-user',
});

const channel = pubnub.channel('quickstart-channel');
const subscription = channel.subscription();

subscription.onMessage = (event) => {
console.log('Message received:', event.message.text);
};

show all 35 lines

Next steps​

You've published and received a message with PubNub. From here, you can go deeper into pub/sub or start adding other capabilities to your application:

  • Pub/Sub overview. Learn about signals, channel groups, and publish options.
  • Presence. Track who is connected to a channel in real time.
  • Data storage. Retrieve messages that subscribers missed while offline.
  • Available SDKs. Find the SDK for your platform or language.

Was this page useful?

Last updated on