JavaScriptWebWebNode.jsPhoneGapReactReduxTitaniumVueJavaScript V4 SDK 4.29.8

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.

SDK getting startedSample app quickstart
  1. PubNub account
  2. Download the SDK
  3. Send messages

Sign in or create an account to create an app on the PubNub 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.4.29.8.js
https://cdn.pubnub.com/sdk/javascript/pubnub.4.29.8.min.js

Use a package manager

yarn add pubnub

Get the source code

Configure PubNub


Create an index.html file with the following content. This is the minimum configuration you need to send and receive messages with PubNub.

Make sure to replace urlToContentDeliveryNetworkVersionOfSDK with the URL to the SDK's CDN URL and replace myPublishKey and mySubscribeKey with your app's publish and subscribe keys from the PubNub Dashboard.

<!DOCTYPE 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="urlToContentDeliveryNetworkVersionOfSDK"></script>
 </head>
 <body>
 <script>

 function letsGo() {

     // Update this block with your publish/subscribe keys
     pubnub = new PubNub({
         publishKey : "myPublishKey",
         subscribeKey : "mySubscribeKey",
         uuid: "myUniqueUUID"
     })
};

 </script>
 </body> 

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

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

Copy the following code to configure your app such that when it receives an event of type PNConnectedCategory, it calls the publishSampleMessage() function.

pubnub.addListener({
        status: function(statusEvent) {
            if (statusEvent.category === "PNConnectedCategory") {
                publishSampleMessage();
            }
        },
        message: function(msg) {
            console.log(msg.message.title);
            console.log(msg.message.description);
        },
        presence: function(presenceEvent) {
            // This is where you handle presence. Not important for now :)
        }
    })

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

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 define the message and the channel you're going to send the message to in the publishPayload variable within the publishSampleMessage() function declaration.

function publishSampleMessage() {
        console.log("Publish to a channel 'hello_world'");

        // 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.
        var publishPayload = {
            channel : "hello_world",
            message: {
                title: "greeting",
                description: "This is my first message!"
            }
        }
        pubnub.publish(publishPayload, function(status, response) {
            console.log(status, response);
        })
    }

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

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

Your index.html file should now look similar to the one below:


 <!DOCTYPE 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.4.29.8.js"></script>
</head>
<body>
<script>

function letsGo() {

    // Update this block with your publish/subscribe keys
    pubnub = new PubNub({
        publishKey : "myPublishKey",
        subscribeKey : "mySubscribeKey",
        uuid: "myUniqueUUID"
    })

    function publishSampleMessage() {
        console.log("Publish to a channel 'hello_world'");
        // 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.
        var publishPayload = {
            channel : "hello_world",
            message: {
                title: "greeting",
                description: "This is my first message!"
            }
        }
        pubnub.publish(publishPayload, function(status, response) {
            console.log(status, response);
        })
    }

    pubnub.addListener({
        status: function(statusEvent) {
            if (statusEvent.category === "PNConnectedCategory") {
                publishSampleMessage();
            }
        },
        message: function(msg) {
            console.log(msg.message.title);
            console.log(msg.message.description);
        },
        presence: function(presenceEvent) {
            // This is where you handle presence. Not important for now :)
        }
    })

    console.log("Subscribing...");

    pubnub.subscribe({
        channels: ['hello_world'] 
    });
};
</script>
</body>

Now, run your app to see if you did everything correctly:

  1. Save index.html and open it in a web browser. Then, using the browser's developer tools, open the JavaScript console.

  2. In the console, type letsGo() and press Enter. This invokes the function, and you should see output similar to the following:

    Subscribing...
    Since we're publishing on subscribe connectEvent, we're sure we'll receive the following publish.
    Object { error: false, operation: "PNPublishOperation", statusCode: 200 }
    Object { timetoken: "15885924757665604" }
    greeting
    This is my first message!
    

Congratulations! You've just subscribed to a channel and sent your first message.

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:

  • defines a letsGo() function
  • configures a PubNub connection
  • adds an event listener
  • subscribes to a channel
  • publishes a message

The letsGo() function is where all the magic happens. This function uses methods in the JavaScript SDK to initialize the PubNub configuration object, subscribe to a channel, and publish a message to it.

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",
        uuid: "myUniqueUUID"
    })

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event. When the sample app receives an event of type PNConnectedCategory, it calls the publishSampleMessage() function. What does this mean?

When you successfully subscribe to a channel, PubNub sends a PNConnectedCategory status event. The app listens for this event, and calls the publishSampleMessage() function when it receives this event, which triggers publishing of the "This is my first message!" message.

The sample app also listens for messages. When it receives a message, the app simply prints the received message's title and description. This is why you see "greeting" and "This is my first message!" displayed in the console.

pubnub.addListener({
        status: function(statusEvent) {
            if (statusEvent.category === "PNConnectedCategory") {
                publishSampleMessage();
            }
        },
        message: function(msg) {
            console.log(msg.message.title);
            console.log(msg.message.description);
        },
        presence: function(presenceEvent) {
            // This is where you handle presence. Not important for now :)
        }
    })

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

PubNub uses the Publish/Subscribe model for realtime 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 publishSampleMessage() function declaration:

function publishSampleMessage() {
        console.log("Publish to a channel 'hello_world'");

        // 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.
        var publishPayload = {
            channel : "hello_world",
            message: {
                title: "greeting",
                description: "This is my first message!"
            }
        }
        pubnub.publish(publishPayload, function(status, response) {
            console.log(status, response);
        })
    }
    (...)

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

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

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.