Introduction to Hapi.js (Part 1)

Arpit Khandelwal
The Resonant Web
Published in
7 min readAug 1, 2019

Preface

Node.js has unarguably become the backbone of the software industry. The increased popularity of JavaScript over the last few years has propelled Node forward in terms of production usage. Perhaps for the first time, JavaScript and Node offer the opportunity to develop entire n-tier applications using a single language.

As it is with all web frameworks, Node provides the essentials for an application — request and response objects, methods to manipulate HTTP requests, ability to interact with a database using popular ORM tools, robust production deployment libraries and more. “Pure” Node apps are stunningly fast, but they lack in the supporting cast of middleware, routing, and plugins that reduce the amount of code needed for a modern web application.

This is where web frameworks shine. This blog post is about hapi.js which is a framework with one of the fastest growing user base, the primary reason being the stability and scalability that hapi provides. Let’s explore more about this wonderful framework in the coming paragraphs.

What is hapi.js?

hapi.js (short for Http-API, pronounced happy and also known as hapi) is an open-source framework for developing scalable web applications. One of the most basic use case of hapi is to build REST APIs. You can build application programming interface (API) servers, websites, and HTTP proxy applications with hapi.js.

It was created by the mobile team at Walmart Labs — led by Eran Hammer to handle their traffic for events like Black Friday, one of the busiest days for online shopping in the U.S. calendar.

Why is there so much of fuss about hapi?

To give you an idea of just why the developer community believes hapi is so robust and dependable, it was able to successfully manage millions of shopping transactions, returns and more at Walmart during Black Friday, arguably the busiest retail shopping day of the year in the U.S.

hapi was able to handle all of Walmart mobile Black Friday traffic with about 10 CPU cores and 28Gb RAM (of course we used more but they were sitting idle at 0.75% load most of the time). This is mind blowing traffic going through VERY little resources. — Eran Hammer

The original versions of hapi used the Express framework. Walmart found that there were limitations with Express that made the framework unsuitable for their particular requirements. Express was missing some key features, so Walmart eventually had hapi evolve to its own stand-alone framework.

Here is a list of some of the great names using hapi in production today:

A hapi community

Building Blocks

Throughout Walmart’s journey of rebuilding their mobile services tier and working with other frameworks, they realised that certain values were vital to building applications in Node for keeping the code intuitive, maintainable, and scalable. As a result, hapi development team centred around the following concepts:

  1. Building value, not infrastructure
  2. Configuration is better than code
  3. Separation of business logic from the transport layer
  4. Open source and community-centric
  5. Ecosystem (Opinionated nature, plugins)
  6. Small modules

Plugins

hapi provides a robust plugin system that allows you to add new features and fix bugs at a fast pace. There are dozens of plugins for hapi, ranging from documentation to authentication, and much more. Some of the most important plugins are listed here.

The benefits of splitting code into plugins reaches beyond just your own code, but easily allows users to share code that is beneficial to everybody. For example, you may have written code specific to Facebook authentication (bell) or a plugin to do something as simple as displaying the routes on startup (blipp).

A benefit of the plugin model and having replaceable parts in hapi is that you’re not bound to a particular way of doing things. If there later comes along a better plugin than the one you’re currently using, then switching it out is far easier than if that part of the code is tightly coupled with the code you want to keep. This applies not just to third-party plugins but anything within your own system as well.

When large companies work on plugins across multiple teams, things like caching can be determined on a per-plugin basis. The teams don’t have to communicate with each other, and even though the plugins run as part of the same server, routes in the different servers can be configured via the plugin to use, for example, different caching mechanisms that are suitable for what that particular piece of code is doing.

Express vs hapi

Both Express and hapi aim to be highly flexible, simple, and extensible. This similarity means that both have easy-to-use APIs, they’re highly modular, and can support your application as it grows potentially very large. The learning curve for these frameworks, since they are quite straightforward, is low, unlike a more opinionated framework like Meteor. If you are coming from using Express you should be able to quickly pick up Hapi, and vice versa.

There are, however, some philosophical differences between the two frameworks.

  • Hapi.js includes more “batteries” by default than Express does. For instance, when parsing payload from forms to via “POST” requests, with Express, you have to include the body-parser middleware. You then use that to parse the POST payload and use the data from the user. On the other hand, with Hapi, you need no middleware. The payload is parsed for you by the framework itself, and you can access the payload directly on the request object. Little conveniences like that are replete in Hapi.
  • “Middleware” is the name given to software modules that work on HTTP requests in succession before the final output is returned to the user in a response. Express lets you attach middleware to handle each request. Hapi, however, works with plugins that provide middleware functionality.
  • Serving static files is remarkably similar between Hapi and Express. Hapi uses the Inert plugin, whereas Express uses the express.static built-in middleware.

Hapi makes sense if you have a well-defined app idea that fits within sensible defaults for the programming approach. Hapi takes an opinionated approach to things like app security, and its plugins system is not as extensive as the Express middleware ecosystem. If you are a large team, the conventions of Hapi can come in useful to keep your code maintainable. Express, on the other hand, works best if you are after flexibility and making most development decisions on your own.

Request lifecycle

hapi is specifically designed to work in complex enterprise environments where multiple teams work on individual projects or overlapping pieces that must connect into one seamless result. By enabling developers to work on modular, reusable code without being narrowly constrained, developers can concentrate on the core project without trying to erect meta-frameworks or refactor the code.

To show this process in action, consider the typical hapi request lifecycle:

hapi.js request lifecycle

Here you can see that the developer is provided with hooks, in the form of handlers and extensions, to implement the logic. hapi largely stays out of what goes into these hooks. As project complexity grows, the need to decouple functionality and distribute the load also grows. The Hapi server becomes the outward-facing interface (by way of an API or UI), while leveraging a wide array of other technologies to break down monoliths of business logic into smaller, bite-sized pieces (which can in turn be managed by Hapi).

hapi 16 v 17

A quick side note about which version you should use. There was a substantial shift in the framework from 16 to 17 (latest being v18.x), where it went from using callbacks to async/await. This blog post, and the next one (with the starter-kit), will use hapi v18.

A Simple Server

A simple hapi based api server can be coded in a few lines of code as follows:

Save the above as server.js and start the server with the command:

node server.js

Now you'll find that if you visit http://localhost:3000 in your browser, you'll see the text “Hello, world!”, and if you visit http://localhost:3000/node you'll see “Hello, node!”.

Part 2

Thanks for reading the first part from a series of two articles on hapi. If this is enough to raise your interest in using this adaptable framework, be sure to check out the second part here.

It contains a detailed walkthrough of the hapi based starter-kit app built by me, which provides an excellent starting point for all hapi developers to use in their own production environments.

If it was interesting or helpful to you, please do press the 👏 clap button and help others find this story too.

Did you know you could give up to 50 claps?

--

--