Building a realtime feed with Node.js and AMP - Pusher Blog

June 15, 2017 0 Comments

Building a realtime feed with Node.js and AMP - Pusher Blog

 

 

This blog post was written under the Pusher Guest Writer program.

Something we can’t deny about Accelerated Mobile Pages (AMP) is that they are fast.

On mobile devices, web pages can take several seconds to load. However, AMPs are web pages designed to load near instantaneously due to the limited set of allowed functionality they provide and a distribution system built around caching.

AMP also uses custom elements called AMP components to implement features with complex interactions such as video players or embeddable content.

In this tutorial, we’re going to implement a realtime feed in AMP using two of these components:

In the backend, we’ll use a Node.js/Express web server with EJS as the template engine.

This is how the final application will look:

The amp-live-list component will regularly poll the server for updated content. When a new item is added, a button will be shown, which when clicked, will update the page to show the latest videos (with a simple pagination).

You can find the entire source code of the application on this GitHub repository. Also, you need to take into account that realtime features on AMP pages are limited and you can do a lot more using Pusher in your website or app.

Setting up the project

Let’s start by creating a package.json file for our project:

 npm init

Or if you want to accept all the defaults:

 npm init -y

Next, install body-parser, ejs, express, and moment as dependencies:

 npm install body-parser ejs express moment

The project will have the following structure:

|— views
| |— index.ejs
|- package.json
|- server.js
  • The view directory contains the EJS template for the main page of the app.
  • In the root directory, we can find the package.json file, as well as the file for the Express server (server.js).

Once you have created the necessary files and directory, you’ll be ready to start coding.

Building the Express server

The web server is a standard Express app with an array to hold the information of the videos we’re going to show.

We will have two endpoints:

  • /, with an optional page query parameter, which will render the template with the list of videos (paginated).
  • /new, which will register a new video.

In the server.js file, let’s start by requiring the modules we’re going to use:

 const express = require('express'); const bodyParser = require('body-parser'); const moment = require('moment');

Next, define the array for the videos and a constant for the number of posts that will be shown on a page:

 const posts = []; const pageSize = 5;

Now let’s configure the Express server to use EJS as the view engine and the JSON parsing:

 const app = express(); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));

This is the definition of the route that will present the videos:

 app.get('/', (req, res) => { let currentPage = 1; const totalPosts = posts.length; const pageCount = Math.ceil(totalPosts / pageSize); if(req.query.page) { currentPage = parseInt(req.query.page, 10); } const start = (currentPage - 1) * pageSize; const end = currentPage * pageSize; res.render('index', { posts: posts.slice(start, end), pageSize: pageSize, pageCount: pageCount, currentPage: currentPage, } ); });

As you can see, we are implementing simple pagination, calculating the page count, and the start and end elements of the post array that will be shown based on the optional page query parameter.

Then, in the last lines, the index template is rendered, passing an object with the properties we’ll need.

This is the definition of the route to registering a new video:

 app.post('/new', (req, res) => { const post = { id: posts.length + 1, videoID: req.body.videoID, timestamp: moment().unix(), timestampStr: moment().format(), }; posts.unshift(post); res.status(200).json(post); });

We create a new object with an ID based on the length of the array of posts, the ID of the video to show (req.body.videoID), and a timestamp in Unix and ISO 8601 format (for example, 2017-06-09T08:02:17-05:00). Then we add this object at the beginning of the array with unshift and return a success response.

Finally, let’s start the server with:

 app.listen(3000, () => { console.log('Server listening on port 3000'); });

Building the live blog template

An AMP HTML page will act as the content of the template. A good starting point is the boilerplate code you can find on the Create Your First AMP Page official tutorial.

For our app, we’ll use a modified version of that code. Open the file views/index.ejs and copy the following code:

 <!doctype html> <html amp lang="en"> <head> <meta charset="utf-8"> <script async src="https://cdn.ampproject.org/v0.js"></script> <title>AMP Live Video Blog</title> <link rel="canonical" href="http://localhost/" /> <meta name="viewport" content="width=device-width,minimum-scale=1,initial-scale=1"> <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'> <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script> <script async custom-element="amp-live-list" src="https://cdn.ampproject.org/v0/amp-live-list-0.1.js"></script> <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript> </head> <body> <body> </html>

For this example, we’re not going to need the JSON metadata from Schema.org. It’s optional but required to make your content eligible to appear in the Google News carousel.
However, we need to keep the canonical link reference, as it is required for the page to be valid. This link must point to itself (the AMP version of the page), so it’s just changed to:

 <link rel="canonical" href="http://localhost:3000/" />

Refer to this page to know more about both options.

AMP allows the use of custom fonts with some restrictions. This page uses the Roboto font:

 <link href='https://fonts.googleapis.com/css?family=Roboto' rel='stylesheet'>

All AMP components used must be imported in the header. The following are the scripts for the YouTube and live list components we’re going to use:

 <script async custom-element="amp-youtube" src="https://cdn.ampproject.org/v0/amp-youtube-0.1.js"></script> <script async custom-element="amp-live-list" src="https://cdn.ampproject.org/v0/amp-live-list-0.1.js"></script>

In addition to the boilerplate style, we’re going to use some custom CSS styles. Since AMP can’t reference external stylesheets, all styles must live in the head of the document with some restrictions, so let’s add our custom CSS inside a <style amp-custom> tag in the head of the document:

 <!doctype html> <html amp lang="en"> <head> ... <style amp-custom> body { font-family: 'Roboto', sans-serif; background: #EDEDED; } .header { color: #fff; padding: 20px 20px; top: 0px; width: 100%; background: #E53935; text-align:center; } #amp-live-list-videos { margin-bottom: 50px; } #live-list-update-button { color: #E53935; border: 1px solid #E53935; padding: .7em .8em; cursor: pointer; background-color: #fff; text-transform: uppercase; letter-spacing: .2em; } .post { margin-top: 20px; } #live-list-update-button { position: fixed; top: 10px; right: 16px; } .pagination { display: inline-block; padding: 0; } amp-live-list [pagination] nav { display: flex; align-items: center; justify-content: center; } .pagination li { display: inline; padding: 10px; list-style-type: none; color: #000; } </style> </head> ... </html>

Now, in the body section, let’s add the page header:

 <!doctype html> <html amp lang="en"> <head> ... </head> <body> <div class="header"> <h1>AMP Live Video Blog</h1> </div> </body> </html>

And the amp-live-list component:

 <!doctype html> <html amp lang="en"> ... <body> ... <amp-live-list id="amp-live-list-videos" data-poll-interval="15000" data-max-items-per-page="<%= pageSize %>" <% if (currentPage > 1) { %> disabled <% } %> > </amp-live-list> </body> </html>

The id attribute identifies the amp-live-list component since multiple live lists are allowed on a single page.
The data-poll-interval attribute specifies how frequently the component will poll new data (in milliseconds). The minimum interval is fifteen seconds.
The data-max-items-per-page specifies the maximum number of items displayed on the page.
If we’re not on the first page, we’re going to add the disable attribute so the component stops polling for new data. (Since new posts will be added to the first page due to how the pagination mechanism works, there’s no need to poll the server if the user isn’t on that page.)

In this example, the amp-live-list component contains three elements as direct children.

The first element is a button with the event on="tap:[ID_OF_THE_LIVE_LIST_COMPONENT].update" to load the latest changes from the server. This button is required and it will appear when new changes are discovered. These changes won’t be shown to the users until they click the button:

 <!doctype html> <html amp lang="en"> ... <body> ... <amp-live-list ... > <button id ="live-list-update-button" update on="tap:amp-live-list-videos.update" > You have updates </button> </amp-live-list> </body> </html>

The second element is <div items>, the list of items to show. These items are required to have a unique id and a data-sort-time attribute (a timestamp used for sorting entries. Higher timestamps will be inserted before older entries):

 <!doctype html> <html amp lang="en"> ... <body> ... <amp-live-list ... > ... <div items> <% posts.forEach((post) => { %> <div class="post" id="<%= post.id %>" data-sort-time="<%= post.timestamp %>"> <amp-youtube width="480" height="270" layout="responsive" data-videoid="<%= post.videoID %>" /> </div> <% }) %> </div> </amp-live-list> </body> </html>

For each post, we’re using an amp-youtube component to render the video. You can find out more about this component here.

Finally, the third element is <div pagination></div> element. It’s our responsibility to insert within this element any markup needed for pagination (which in this case is only shown if there’s more than one page):

 <!doctype html> <html amp lang="en"> ... <body> ... <amp-live-list ... > ... <div pagination> <nav aria-label="amp live list pagination"> <% if (pageCount > 1) { %> <ul class="pagination"> <% for (var i = 1; i <= pageCount; i++) { %> <% if (currentPage == i) { %> <li><%= i %></li> <% } else { %> <li><a href="/?page=<%= i %>"><%= i %></a></li> <% } %> <% } %> </ul> <% } %> </nav> </div> </amp-live-list> </body> </html>

And we’re done. You can find out more about how the amp-live-list component works on this page.

Testing the application

Execute the web server with:

 node server.js

If you go to http://localhost:3000, you’ll see a blank page:

It’s recommended you use Chrome because you can validate an AMP page just by adding #development=1 to the URL, for example, http://localhost:3000/?page=1#development=1 and view the result of the validation in the Chrome DevTools console:

To register videos, you can use a tool like Postman to hit the http://localhost:3000/new endpoint with a JSON payload like the following:

 { "videoID": "[YOUTUBE_VIDEO_ID]" }

Or curl:

 # POST curl -H "Content-Type: application/json" -X POST -d '{"videoID":"[YOUTUBE_VIDEO_ID]"}' http://localhost:3000/new # In Windows, change single quotes to quotation marks and escape the ones inside curly brackets curl -H "Content-Type: application/json" -X POST -d "{\"videoID\":\"[YOUTUBE_VIDEO_ID]\"}" http://localhost:3000/new # Or use file, for example data.json curl -H "Content-Type: application/json" -X POST --data @data.json http://localhost:3000/new

After a few seconds (fifteen at most), the button to load the new videos should be visible:

And after adding more than five videos, the pagination links will be shown:

In addition, if you look at the network tab of the console, you’ll see that a request to the server is made every fifteen seconds:

Conclusion

You’ve now learned how to implement a realtime feed with pagination on AMP using the amp-live-list component. We have covered insertions, but updates and deletions are also supported by this component. Here’s an example of how to update existing list items.

Remember that you can find the source code of this app in this GitHub repository.


Tag cloud