Build a simple realtime app with hapi.js and Pusher Channels

  • Olayinka Omole
April 29th, 2018
You need Node and npm installed on your machine. A working knowledge of JavaScript and ES6 syntax will be helpful.

Hapi.js is a modern Node.js framework that has been gaining popularity in the JavaScript world. In this tutorial, we will introduce hapi.js. We will use it to build a realtime application with the help of the powerful Pusher Channels API.

Our application will store contacts and make them available to all its users in real time. You can see it action in the image below:

Requirements

To follow along with this tutorial, you would need the following installed:

You also need to have a working knowledge of JavaScript and ES6 syntax.

Introduction to hapi.js

Hapi, short for HTTP **API Server was developed by the team at Walmart Labs, led by Eran Hammer. It embraces the philosophy that configuration is better than code. It also provides a lot more features out of the box than other popular JavaScript frameworks like Express.js and Koa.

Introduction to Pusher

Pusher is a service that makes it easy to add realtime functionality to various applications. We will use it in our application. Sign up for a free account here, create an app, and copy out the app credentials (App ID, Key, and Secret) from the "App Keys” section.

Setup and configuration

Let us get started by setting up our project. Create a folder with the project name hapi-contacts and change directory to that folder in your terminal:

    mkdir hapi-contacts && cd hapi-contacts

To initialize the application, run the following command:

    npm init -y

Tip: The -y or --yes flag helps to create a package.json file with default values.

Next, we will install hapi.js and other needed packages to our application. The inert package helps serve static files and directories in a hapi.js application, while the pusher package helps us interact with the Pusher API. Run this command to install the needed packages:

    npm i hapi inert pusher

Now, we can create the files needed for our application. We will maintain a very simple file structure:

    ├── hapi-contacts
        ├── app.js
        └── public
            └── index.html

The app.js file will contain all the server-side logic for our application, while the index.html file will contain the view for our application and the client-side logic.

Building our backend

Starting a server

We will start off building out the backend for our app by starting a hapi.js server. We can do this by adding the following content to our app.js file:

    // ./app.js

    // Require needed modules
    const Hapi = require('hapi');

    // Initialise Hapi.js server
    const server = Hapi.server({
      port: process.env.port || 4000,
      host: 'localhost'
    });

    const init = async () => {
      // start server
      await server.start();
      console.log(`Server running at: ${server.info.uri}`);
    };

    // handle all unhandled promise rejections
    process.on('unhandledRejection', err => {
      console.log(err);
      process.exit(1);
    });

    // Start application
    init();

In the code above, we first require the hapi package, then initialize it to the server variable. We use this variable in the init() function to start our server with the server.start() method. Finally, we add a process.on(``'``unhandledRejection``'``) event listener to handle all unhandled or “un-caught” promise rejections and log the errors to console.

To run the app:

    node app.js

Note: visiting localhost:4000 at this point will return a 404 as we have not defined any routes yet.

Defining Routes

Next, we will define routes for adding and removing contacts from our application. We will use Pusher to trigger events and broadcast the details of new and deleted contacts to all the application’s users.

Note: in reality, the contact details should be persisted to some form of database or store. We did not do this in this tutorial as it is beyond its scope. You can implement a data store in your own version of the app!

First we initialize Pusher before the init() function:

    // ./app.js
    // ...
    const Pusher = require('pusher');

    // Initialize Pusher
    const pusher = new Pusher({
      appId: 'YOUR_APP_ID',
      key: 'YOUR_APP_KEY',
      secret: 'YOUR_APP_SECRET',
      cluster: 'YOUR_APP_CLUSTER',
      encrypted: true
    });

In the code above, we require the pusher package and initialize Pusher with the credentials we got from the Pusher dashboard. Remember to replace YOUR_APP_ID and similar values with the actual credentials.

Then we define our routes in the init() function:

    // ./app.js
    // ...
    const init = async () => {
      // store contact
      server.route({
        method: 'POST',
        path: '/contact',
        handler(request, h) {
          const { contact } = JSON.parse(request.payload);
          const randomNumber = Math.floor(Math.random() * 100);
          const genders = ['men', 'women'];
          const randomGender = genders[Math.floor(Math.random() * genders.length)];
          Object.assign(contact, {
            id: `contact-${Date.now()}`,
            image: `https://randomuser.me/api/portraits/${randomGender}/${randomNumber}.jpg`
          });
          pusher.trigger('contact', 'contact-added', { contact });
          return contact;
        }
      });

      // delete contact
      server.route({
        method: 'DELETE',
        path: '/contact/{id}',
        handler(request, h) {
          const { id } = request.params;
          pusher.trigger('contact', 'contact-deleted', { id });
          return id;
        }
      });

      // start server
      await server.start();
      console.log(`Server running at: ${server.info.uri}`);
    };
    // ...

We define two routes in the init() function. In hapi.js, we can define routes with the server.route() method. The main parameters needed to make use of this method are the path, the method, and a handler. You can read more about routing in hapi.js in their docs.

Triggering events

When a request is made to the '``POST /contact``' route, we first retrieve the contact details in the payload sent to the API via the request.payload object and assign the details to the contact object. Next, we generate an ID and a random avatar, then assign these details to the same contact object. Finally, using Pusher, we trigger a contact-added event on the contact channel, sending the contact object as data to be broadcasted.

The trigger() method has the following syntax:

    pusher.trigger( channels, event, data, socketId, callback );

You can read more about it here.

Note: we are broadcasting data on a public Pusher channel as we want the data to be accessible to everyone. Pusher also allows broadcasting on private and presence channels, which provide functionalities that require authentication. Their channel names are prefixed by private- and presence- respectively.

Similarly, when a request is made to the '``DELETE /contact``' route, we trigger a contact-deleted event on the contact channel and broadcast the ID of the deleted contact.

Building our frontend

Serving static files

To serve the index.html file, we make use of inert, a package that helps us serve static files in a hapi.js application. According to their documentation:

Inert provides handler methods for serving static files and directories, as well as adding an h.file() method to the toolkit, which can respond with file-based resources.

To start serving the index.html page on the '``GET /``' route, let us update the app.js file:

    // ./app.js
    // ...
    const Path = require('path');
    const Inert = require('inert');

    const server = Hapi.server({
      port: process.env.port || 4000,
      host: 'localhost',
      routes: {
        files: {
          relativeTo: Path.join(__dirname, 'public')
        }
      }
    });
    const init = async () => {
      // register static content plugin
      await server.register(Inert);

      // index route / homepage
      server.route({
        method: 'GET',
        path: '/',
        handler: {
          file: 'index.html'
        }
      });
      // ...

    };
    //...

In the code block above, we add the routes.files option when creating the server. This specifies that we will be serving static files from the public directory.

The GET / route definition simply uses the file handler to serve the index.html file.

Now, we can add some markup to our view. We will import a CSS framework called Bulma to take advantage of some premade styles. We will also create a simple form and an area for displaying our contacts. Add the following code to the index.html file:

    <!-- ./public/index.html -->
    <html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Hapi.js Realtime Application!</title>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css">
    </head>
    <body>
        <section class="section">
            <div class="container">
                <div class="intro">
                    <h1 class="title">Hello</h1>
                    <p class="subtitle">
                        Welcome to <strong class="has-text-primary">HapiContacts</strong>!
                    </p>
                </div>
                <hr>
                <section class="columns">
                    <div class="column is-two-fifths">
                        <h4 class="title is-3">
                            Add Contact
                        </h4>
                        <form id="addContactForm">
                            <div class="field">
                                <label class="label">Name</label>
                                <div class="control">
                                    <input name="name" required class="input" type="text" placeholder="e.g Alex Smith">
                                </div>
                            </div>
                            <div class="field">
                                <label class="label">Phone Number</label>
                                <div class="control">
                                    <input name="phone" required class="input" type="text" placeholder="e.g. 234-80-988-7676">
                                </div>
                            </div>
                            <div class="field">
                                <label class="label">Address</label>
                                <div class="control">
                                    <textarea name="address" required class="textarea" placeholder="Glover road"></textarea>
                                </div>
                            </div>
                            <div class="field">
                                <div class="control">
                                    <button class="button is-primary">Save</button>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="column">
                        <h4 class="title is-3">
                            Contacts
                        </h4>
                        <div id="contacts-list" class="columns is-multiline"></div>
                    </div>
                </section>
            </div>
        </section>
    </body>
    </html>

Making API calls

Next, let us define functions for adding and deleting contacts. To make requests to our API endpoints, we will use the JavaScript Fetch API. Let us update the index.html file:

    <!-- ./public/index.html -->
        <script>
            const form = document.querySelector('#addContactForm');
            form.onsubmit = e => {
                e.preventDefault();
                const contact = {
                    name: form.elements['name'].value,
                    phone: form.elements['phone'].value,
                    address: form.elements['address'].value
                }
                fetch('/contact', {
                    method: 'POST',
                    body: JSON.stringify({ contact })
                })
                    .then(response => response.json())
                    .then(response => form.reset())
                    .catch(error => console.error('Error:', error));
            }
            const deleteContact = id => {
                fetch(`/contact/${id}`, { method: 'DELETE' })
                    .catch(error => console.error('Error:', error));
            }
        </script>
    </body>
    </html>

In the code block above, we define an event listener for the onsubmit event, which will be fired once our form for adding contacts is submitted. In the listener function, we make an API call to the '``POST /contact``' endpoint using the intuitive JavaScript Fetch API.

We also define the deleteContact() function to help make API calls to delete contacts from our app.

Note: we make use of the JavaScript Fetch API for making AJAX requests. It is promise-based and more powerful than the regular XMLHttpRequest. A polyfill might be needed for older browsers. A great alternative to the Fetch API is axios.

Listening for events

Our last step in creating our app is to define listeners for the various events we are triggering via Pusher.

Before we define listeners, we need to include the Pusher JavaScript library. This will help us communicate with the Pusher API from the client-side. We will also initialise Pusher with the credentials we have previously gotten from the Pusher dashboard. Updating index.html:

    <!-- ./public/index.html -->
        <script src="https://js.pusher.com/4.0/pusher.min.js"></script>
        <script>
            // ...
            const pusher = new Pusher('APP_KEY', {
                cluster: 'APP_CLUSTER',
                encrypted: true
            });
        </script>
    </body>
    </html>

Note: don't forget to replace APP_KEY with its actual value.

Next, we will define listener functions for the various events we are triggering via Pusher. Updating index.html:

    <!-- ./public/index.html -->
        <script>
            // ...
            const channel = pusher.subscribe('contact');

            channel.bind('contact-added', ({ contact }) => {
                appendToList(contact)
            });

            channel.bind('contact-deleted', ({ id }) => {
              const contact = document.querySelector(`#${id}`);
              contact.parentNode.removeChild(contact);
            });

            // helper function that appends new posts
            // to the list of blog posts on the page
            const appendToList = data => {
                const html = `
                    <div class="column is-half" id="${data.id}">
                        <div class="card">
                            <div class="card-content">
                                <div class="media">
                                    <div class="media-left">
                                        <figure class="image is-48x48"><img src="${data.image}"></figure>
                                    </div>
                                    <div class="media-content">
                                        <p class="title is-4">${data.name}</p>
                                        <p class="subtitle is-6">${data.phone}</p>
                                    </div>
                                </div>
                                <div class="content"><p>${data.address}</p></div>
                            </div>
                            <footer class="card-footer">
                                <a onclick="deleteContact('${data.id}')" href="#" class="card-footer-item has-text-danger">
                                    Delete
                                </a>
                            </footer>
                        </div>
                    </div>`;
                const list = document.querySelector("#contacts-list");
                list.innerHTML += html;
            };
        </script>
    </body>
    </html>

Tip: you can also use Pusher.logToConsole = true; to debug locally

In the code block above, first, we subscribe to the contact public channel on which we trigger all our events with the pusher.subscribe() method. We then assign that subscription to the channel variable.

Next, we define listeners for the contact-added and contact-deleted events using the channel.bind() method. The method has the following syntax:

    channel.bind(eventName, callback);

You can read more about client events in Pusher here.

Lastly, we define a helper function called appendToList() to help us generate and append HTML for each new contact added.

Now, we have a functional realtime hapi.js application! You can run the app with the following command:

    node app.js

The entire code for this tutorial is hosted on Github.

Conclusion

In this tutorial, we have learned how to create a realtime application from scratch using the intuitive hapi.js framework and Pusher. Although hapi.js is a little different from what many JavaScript developers are used to (the Express way), it introduces its own advantages and may just be a good pick for your next project.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.