Comments Feed Tutorial

To learn how to use Feeds API, let's build something with it! Feeds is an excellent fit for building realtime comments walls. By the end of this tutorial you will have created a rudimentary comments wall from scratch that looks like this:

You can download the completed code for this tutoarial from this GitHub repo.

Publishing Items From the Dashboard

The Feeds service stores a list of “feed items”. To build your comments wall, you'll store each comment as a feed item. The post “I love this song!” is one such feed item. Here's how your items will be stored in Feeds:

Feed items are stored in an instance of the Feeds service. You can create a new instance of the Feeds service on the homepage of the Pusher Platform dashboard. Once it's created, you can view your instance locator and key on the “Keys” page. These are used to connect the SDKs to your instance of Feeds.

The Pusher Platform dashboard has an integrated feed inspector. You'll use this to create your first few feed items. Click on “Inspector”. By default you will already have a single feed with ID playground. For this tutorial we'll create a new feed with ID comments. You can do this by typing “comments” in the text box which currently reads “playground”.

Next, add a few items to the new feed. Each feed item has a JSON object as its body. Use the format "comment": "I love this song!". With this format, we can add new properties to items later in this tutorial. Use your imagination to add two or three items:

Subscribing From the Comments Wall Web Page

Now you have some feed items, let's start making the comments wall website! Make a new directory for your code, and a directory static within that, and Copy-paste this into static/index.html, replace YOUR_INSTANCE_LOCATOR with your instance locator from the dashboard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<!DOCTYPE html>

<html>
<head>
  <title>Feeds comments wall</title>
  <link
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
    rel="stylesheet">
  <script src="https://unpkg.com/@pusher/feeds"></script>
  <script>
    const commentsFeed = new Feeds({
      instanceLocator: "YOUR_INSTANCE_LOCATOR"
    }).feed("comments");

    // Subscribe to items published to the `comments` feed.
    commentsFeed.subscribe({
      // Get 10 previously published items as our initial state
      previousItems: 10,
      // On each new item, append it to the `comments` ul element
      onItem: ({ created, data }) => {
        const itemEl = document.createElement("li");
        itemEl.textContent = data.comment;
        document.getElementById("comments").prepend(itemEl);
      }
    });
  </script>
</head>

<body style="padding: 30px;">
  <div style="border-style: solid; width: 70%; margin: auto; padding: 10px;">
    <h3>Comments</h3>
    <ul id="comments"></ul>
  </div>
</body>
</html>

Open the file in your browser and you should see something that looks like the below.

Now for some magic! Back in the Inspector, add a new item to the comments feed, with the following body:

1
{ "comment": "Readers will receive this comment in realtime" }

Instantly, this item is added to your comments wall, like in the image below:

Your onItem callback receives previous items when first subscribing, and then receives new items as they are published.

Publishing From Your Comments Wall Web Page

You've now seen how publishing works from the Inspector in the dashboard. This is great for getting started, but you will want to post updates from your web page, where you can create an appropriate user interface for writing comments. Here's what we want it to look like:

Publishes to feeds must happen from your server. When a user wants to submit a comment, the client side app must make a request to your server with the post content, which in turn publishes it to the Feeds service.

Setting Up Express

First you should get a basic server up and running to serve the static site we already have. In this tutorial we will use Express on the server.

Let's create an Express server to serve this static HTML file. First initialize a Node.js package and install Express:

1
2
$ npm init --yes
$ npm install express --save

Then create your index.js file:

1
2
3
4
5
6
const express = require("express");

const app = express();
app.use(express.static("static"));
app.listen(5000);
console.log("Listening on port 5000");

And run the server:

1
$ node index.js

Then open http://locahost:5000/ in your browser to make sure everything is woking as intended.

Setting Up Feeds

Now that we've got an Express server up and running, let's install the Feeds server SDK:

1
$ npm install pusher-feeds-server --save

The client will publish comments as the POST request body, so we'll need to install the Express body parser:

1
$ npm install body-parser --save

Open the index.js file where you previously defined the Express server. Let's import the dependencies you just installed, and initialise an instance of the Feeds object. You can find your instance key on the “Keys” page of the dashboard.

1
2
3
4
5
6
7
const bodyParser = require("body-parser");
const Feeds = require("pusher-feeds-server");

const feeds = new Feeds({
  instanceLocator: "YOUR_INSTANCE_LOCATOR_HERE",
  key: "YOUR_INSTANCE_KEY_HERE"
});

Finally we need to define a request handler which handles new comments that are published from the client, which in turn publishes them to the Feeds service.

1
2
3
4
5
6
7
8
app.use(bodyParser.json());

app.post("/comments", (req, res) => {
  feeds
    .publish("comments", req.body)
    .then(() => res.sendStatus(204))
    .catch(err => res.status(400).send(err));
});

The publish method returns a promise of a server response, which can tell us whether the publish succeeded. There are several reasons a publish might fail, for example your device might be offline. To find out the status of a publish call, check the promise using then and catch.

To test it works, run the server, and make a request to it with cURL. You should see a comment appear on the web page!

1
2
3
curl http://localhost:5000/comments \
-H 'Content-Type: application/json' \
-d '{ "comment": "An interesting comment" }'

Now let's add an element to the client which lets you submit a comment to your server endpoint in static/index.html.

Start by adding a text input and a “Publish” button above the existing comments <ul>.

1
2
<input id="comment" type="text" style="width: 79%;">
<button type="button" style="width: 19%;" onclick="publishComment()">Publish</button>

Then add this JavaScript so that when the button is clicked, the page will take the content of the input, post it to your server, then clear the text input so another comment can be written.

1
2
3
4
5
6
7
8
9
function publishComment() {
  const xhr = new XMLHttpRequest();
  xhr.open("POST", "/comments", true);
  xhr.setRequestHeader("Content-Type", "application/json");
  xhr.send(JSON.stringify({
    comment: document.getElementById("comment").value,
  }));
  document.getElementById("comment").value = "";
}

Open this up in multiple browser windows and try publishing a few comments. Congratulations, you've created a complete realtime comments wall!

In part 2 we'll see how you can add a feed per user to the website you just created.

Did you find this document useful?

We are always striving to create the most accurate and informative docs as possible. If there is something especially wrong (or right) here then please let us know.