Getting Started

To start with, we'll get up & running with a basic implementation of Feeds. We'll learn how to subscribe and publish to a feed, as well as fetch older items upon subscribe - great for when users lose their connection.

Installing & Importing

First of all, set up a basic html page and get the JavaScript client SDK.

1
2
3
4
5
6
7
8
9
10
11
12
<!DOCTYPE html>
<html>
  <head>
    <title>Feeds getting started</title>
    <script src="https://unpkg.com/pusher-feeds-client@0.10.0"></script>
  </head>
  <body>
    <script>
      // Your code goes here
    </script>
  </body>
</html>
If you'd rather install the SDK yourself, you can find it on GitHub.

Setting Up

Now we need to initialize a Feeds object with your instanceLocator:

1
2
3
const feeds = new Feeds({
  instanceLocator: "YOUR_INSTANCE_LOCATOR",
});

Subscribing to a Feed

You can subscribe to a feed before it has any items. Let's make a new feed with ID playground and subscribe to it. (Ignore the commented line, we're getting there!)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const playground = feeds.feed("playground");

playground.subscribe({
  // previousItems: 5,
  onOpen: () => {
    console.log("Feeds: Connection established");
  },
  onItem: item => {
    console.log("Feeds new item:", item.data);
    document.body.innerHTML +=
      `<p>${JSON.stringify(item.data)}</p>`;
  },
  onError: error => {
    console.error("Feeds error:", error);
  },
});

To check things are working, open the page in a browser and check the console for the “Connection established” message.

Publishing Items to the Feed

Try using the inspector on your dashboard to publish an item to the playground feed with the following data - the item handler you set up in step 3 should receive the item:

1
{ "message": "Hello world!" }

Getting Some Previous Items

Uncomment the previousItems option from step 3.

1
previousItems: 5,

If you refresh the page, you should see the last five items come in before any new ones. These are handled by the onItem callback in just the same way as new publishes!

Publish From the Server

You'll want to be able to publish to feeds programatically - let's try using the Node.js server SDK to publish some items to our feed.

1
2
3
4
5
6
7
8
9
10
const Feeds = require("pusher-feeds-server");

const feeds = new Feeds({
  instanceLocator: "YOUR_INSTANCE_LOCATOR",
  key: "YOUR_KEY",
});

feeds.publish("playground", {
  message: "Hello from the server!",
});

That's it! You can get the full source of all the above steps on GitHub.

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.