Contact

Hapi.js and Express.js are Node.js frameworks. For those who are new to the field of development, here is a simple introduction on what Node.js is. Node.js is a very popular JavaScript runtime that allows the users to run JavaScript code on the browser. This framework is built on Google Chrome’s V8 VM engine, which in turn supports JavaScript in the Chrome browser.

There are so many different kinds of Node.js frameworks and each helps you to build large scale, scalable web applications in real time with JavaScript alone. As the demand grew, there arose the need for frameworks that would help build high speed real time end to end applications, without using third party web server, or any kind of tool, technology or app server. It is the job of the developer to select a framework that would best serve his purpose. He can choose from among the following: Hapi, Express, Koa, Meteor, Derby, Flatiron, Mean.IO, Mojito, Socket, Stream, Sail.js.

Ultimately, it is the developer who decides which framework to use. If you are looking for greater flexibility or need something that is perfect for grounds up development, then Express, Hapi and Koa would be the possible options. If you choose Mojito, Derby, Meteor and Mean.IO, then it means you are looking for a framework with a standard structure, but with lesser flexibility. If you are in the mood for some specialised Node.js API frameworks to create API, then LoopBack, actionHero.js and Restify are good choices. In this article, however, we discuss two of them - Hapi and Express to know which one scores better than the other in certain circumstances.

HapiHapi.js is an open source framework built on top of Node.js that creates web applications and services. The rich framework was designed by Eran Hammer, who grew in popularity as the Sr. Architect of Mobile Platform at Walmart and responsible for building powerful Walmart mobile APIs. Some developers are of the opinion that Hapi (short form of HttpAPI) is termed so because it makes developers happy because it deals more with configuration and less with code. Whether that’s true or not, Hapi was actually devised as an answer to the problems developers were having with Express.

Before installing Hapi, you have to install Node.js. As Node.js uses an event-driven and non-blocking I/O model, it is extremely lightweight and efficient, making it easy for developers to run data intensive real-time applications capable of running across distributed devices.

ExpressExpress.js was initially created by TJ Holowaychuk in 2010 and was believed to be the first very successful de facto http server framework. Over the years, it started to stagnate, but was kept afloat by devoted key contributors. TJ Holowaychuk first released Express in June 26th 2009. It is integrated with minimal and flexible Node.js web application and integrated with a robust set of features. And thanks to a horde of HTTP utility methods and middleware, you can create robust API in the nick of time. Node.js features are kept intact, but provides its own set of basic web application features.

To leverage Express to its maximum capacity, you can use the following modules as well:

  • body-parser - middleware for handling JSON, Raw, Text and URL encoded form data
  • muster - middleware for handling multipart-form-data
  • cookie-parser - An interface to a utility where cookie values are keyed in and set on the client browser.

Thus, Express.js is a web framework that works on the basis of core Node.js http module and middleware. It helps you create very basic apps to highly scalable full stack web applications. Express listens to requests when the app is running and each request is processed through a specific chain of middleware and routes. The normal process is from top to bottom with an execution flow that you can control.

Comparison

Before going into the comparison between Hapi and Express, let’s look at the quick facts about the two. It would help keep the important pointers in mind when you go forward:

Quick Facts about Hapi

  • Hapi is configuration-centric
  • It has authentication and authorization built into the framework
  • It was released in a battle tested atmosphere and has really proven its worth
  • All the modules have 100% test coverage
  • It registers the highest level of abstraction away from core http
  • Easily compassable via plugin architecture

Quick Facts about Express

  • It is the most popular node http framework so far
  • The primary building block is middleware
  • Is a minimal and flexible framework
  • Doesn’t obscure the Node.js features
  • Robust set of features for web and mobile applications
  • Has better front end tooling like web packs, starter packs, boiler plates

Continuous comparison tests have been made on both Express and Hapi to ensure which is the winner. Each year tests are conducted to check how the performance of these two frameworks has changed. Tests were conducted to check the basic capabilities of both the frameworks and to check the relative overhead these frameworks add while handling a request, and not just considering their basic utility and performance features. The final result would also be dependent on the network conditions, the applications built using them and the environment in general.

The comparison done here doesn’t intend to place framework above the other, but it rather depends on the features you need while building rich web apps. Raygun conducts tests on different frameworks every year, as will be explained here. (Raygun is a website that helps you spend more time developing good apps and spend little or no time at fighting the repercussions, because at the end of the test, you will know which framework to use, and which not to). In the test conducted last year (2015), Raygun made out a graph like this with Hapi, Express and Restify with no middleware:

Credits: https://raygun.com/blog/2015/03/node-performance-hapi-express-js-restify/

The above graph shows that Restify is the clear winner. The test is conducted on the basis of receiving and returning a static string using “Hello World”, the results are the theoretical number of requests handled each second. The focus here is the data that comes in the form of requests per second as it is the most useful metric for calculation. The test was conducted using the Apache HTTP server benchmarking tool to generate requests to the server.

The parameters were set by putting in 50,000 connections, 100 concurrent connections and 20-second timeout per request. In order to segregate the action of different frameworks and to know how they handled the requests, a Connection header was set for all the responses so none of the connections were left open. The node performance result that you see below is the average of five different tests.

Credits : https://raygun.com/blog/2016/06/node-performance/

This gives the proof that Raw node.js was the fastest, while Hapi registered at a speed that is almost half of Raw node.js. Express registered itself as slightly faster than Hapi. From the table, it is also clear that both Hapi and Express are best suited for building heavy browser apps. Other frameworks like Restify, which you see had scored well in the table, will not be a good choice when you are designing a richer web app. The frameworks are quite different when you create routes.

Here is an example of that: Let’s look at a framework where we create a route that responds to GET request and comes back with “Hello World”Express

app.get('/', function (req, res) {
res.send('Hello World!');
});

Express displays a strong resemblance to Sinatra, using an API similar to the popular Ruby library:get '/' do 'Hello world!'
End

Credits: https://expressjs.com/en/starter/hello-world.html

Hapi

server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});

Credits : http://hapijs.com/tutorials/getting-started?lang=en_US

Here are some differences when you use Express and Hapi, a few of which you have probably noted anyway. The configuration object, server.routetakes a single argument. For Hapi, HTTP verb does not dictate the API method to be used as it is always server.route; whereas in Express it is the app.all()method . To make the handler respond to any HTTP verb, the method is to be specified as “*”.

Performance

When you compare Express and Hapi as against their capabilities for web application design and development point of view, which one scores more? Many people say that Hapi is a better choice performance wise, let’s explore why. Hapi uses a different routing mechanism, which can do faster lookups, and take registration order into account. Nevertheless, it is quite limited when compared to Express. And thanks to the Hapi plugin system, it is possible to isolate the different facets and services that would help the application in many ways in the future.

Performance wise, ultimately it is left to the developer’s own devices to make his decision on choosing Express or Hapi. But most of the developers vote for Hapi even though it takes a lot of code. The benefit of having a lot of code is that it can be easily changed and configured, which is why it is the most preferred choice for enterprise applications.

The slow learning curve of Express also turns against it many a time. However, both the frameworks are good at solving the same problem - provide a convenient API to build HTTP servers in node. Both Hapi and Express use concepts that are used mainly in high-level frameworks in the following: routing, handlers, plugins, authentication modules. Though they may not use the same terms, the procedure is similar. It would go something like this:

Route creation Trigger function when route is requested; generating response

Responding to the request

Express
app.get('/', function (req, res) {
getSomeValue(function (obj) {
res.json({an: 'object'});
});
});

Hapi
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
getSomeValue(function (obj) {
reply(obj);
});
}
});

Credits: http://stackoverflow.com/questions/30469767/how-do-express-and-hapi-compare-to-each-other

The main difference between Hapi and Express is that Hapi provides a lot more than the latter. Express, on the other hand, is very minimal. It gives you a small API, and you need to add more modules for added functionalities. If you want to send more content types along that particular route, you need to first clarify it depending on which content-type header it belongs to and then you will have parse it accordingly.

Hapi is well known for its rich feature set with figuration options, not asking for code to be written for each requirement. If a request body is configured in memory, correctly parsed and automatically based on the content type, before running the handler, it would look like this:

server.route({
config: {
payload: {
output: 'data',
parse: true
}
},
method: 'GET',
path: '/',
handler: function (request, reply) {
reply(request.payload);
}
});

Credits: http://stackoverflow.com/questions/30469767/how-do-express-and-hapi-compare-to-each-other

Creating a Server using Hapi

Before getting started with the server, you need to install Hapi, of course. The process goes like this: Run: npm init and follow the prompts to create a package.json file. Next, Run: npm install --save hapi to install Hapi and save it in your package.json as a dependency for your project

Follow the code snippet below to create a server using Hapi

'use strict';
const Hapi = require('hapi');
const server = new Hapi.Server();
server.connection({ port: 3000 });
server.start((err) => {
if (err) {
throw err;
}
console.log(`Server running at: ${server.info.uri}`);
});

Credits: http://hapijs.com/tutorials/getting-started?lang=en_US

So now you have installed Hapi and created a server. While creating a server connection, you can add a hostname, IP address and a UNIX socket file or Windows named pipe to bind the server to.Creating a Server using ExpressAs an example, you can start by creating a directory named myapp, change to it and run npm init . Then, follow the installation guide in the Express website to install express as a dependency, In the myapp directory, create a file named app.js and include the following code:

var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});

Credits: https://expressjs.com/en/starter/hello-world.html

The app starts a server and listens on port 3000 for connections. The app responds with “Hello World!” for requests to the root URL (/) or route. For all other paths, the response will be generated as: 404 Not Found.

Adding Routes to Hapi

Routing is the technique by which application end points are defined and how they handle client requests. Here’s how you add routes to Hapi

server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Hello, world!');
}
});
server.route({
method: 'GET',
path: '/{name}',
handler: function (request, reply) {
reply('Hello, ' + encodeURIComponent(request.params.name) + '!');
}
});
server.start((err) => {
if (err) {
throw err;
}
server.log('info', 'Server running at: ' + server.info.uri);
});
});

Credits - http://hapijs.com/tutorials/getting-started?lang=en_US

Hapi, normally sets the content type based on the data you send. The server is initialized with port number and host, so all you have to do is start the server. When the index route is set up, you can listen for incoming requests.

Adding Routes to Express

Adding routes to Express is a little different from adding routes in Hapi. Here is how a basic routing example would look like:

// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage');
});
// POST method route
app.post('/', function (req, res) {
res.send('POST request to the homepage');
});

Credits: https://expressjs.com/en/guide/routing.html

Creating Plugins

Plugins are central to Hapi and helps you to build modular applications. And Hapi has a very powerful set of plugins that would help you break your application to isolated pieces and reusable utilities.

A very basic plugin is as follows:

'use strict';
const myPlugin = {
register: function (server, options, next) {
next();
}
};
myPlugin.register.attributes = {
name: 'myPlugin',
version: '1.0.0'
};

For an external module, the plugin would look like this:

'use strict';
exports.register = function (server, options, next) {
next();
};
exports.register.attributes = {
pkg: require('./package.json')
};

In the first example, the name and version attributes are set specifically. In the external module example, pkg parameter is set with the contents of package.json as its value. Once plugins are set they can be safely registered into the server using three parameters - server, options and next. A single plugin or multiple plugins can be loaded in the following way:

/ load one plugin
server.register(require('myplugin'), (err) => {
if (err) {
console.error('Failed to load plugin:', err);
}
});
// load multiple plugins
server.register([require('myplugin'), require('yourplugin')], (err) => {
if (err) {
console.error('Failed to load a plugin:', err);
}
});

Credits: http://hapijs.com/tutorials/plugins?lang=en_US

Usage

Hapi is the most preferred framework when compared to Express. Hapi is used mainly for large scale enterprise applications. A couple of reasons why developers do not choose Express when creating enterprise applications are: Routes are harder to compose in Express Middleware gets in the way most of the time; each time you are defining the routes, you have to write as many number of codes.

Wrapping Up

Hapi has a light and flexible API, easy to use plugin architecture, where you can isolate in different phases in the modules and change according to requirement. For each and every requirement that you are looking for, you can create the plugin. Hapi also offers an excellent ecosystem for plugins which you don’t get with Express. If you are wondering why Hapi is already not hugely popular yet, is because Express had a head start of about one and half years before Hapi. However, Hapi was created with the idea that configuration is better than code (meaning, you don’t have to write that many code, but is possible to isolate the different things in the plugins), and that the business logic must be separated from the transport layer.

You can choose to go for Express if you are generating a static Javascript and in a hurry. The low learning curve of Express is seen as an advantage by people working on a deadline. You can also choose Express if you have too much tooling and you need a lot of middleware; some people cannot function without middleware. Some people prefer to use Express if they cannot afford to have a large team. Hapi would be the best choice for a developer looking to build RESTful API. Hapi has micro-service architecture and it is also possible to transfer the control from one handler to another based on certain parameters.

With Hapi plugin, you can enjoy a greater level of abstraction around HTTP because you can divvy up the business logic into pieces easily manageable. Another huge advantage with Hapi is that it provides detailed error messages when you misconfigure. Hapi also lets you configure your file upload size by default. If the maximum upload size is limited, you can send an error message to the user conveying that the file size is too large. This would protect your server from crashing because the file uploads will no longer try to buffer a whole file.

The Final Word

Hapi is quite different from the minimalist frameworks whose main aim is to just provide with user-friendly APIs and utilities. Hapi concentrates on giving you a unified framework that aims to makes it easy when you build web applications. The fact that it is open source (right from day one) and community centric also runs in its favor. There is a welcoming community that would answer most of the questions, and addresses the problems faced by developers, while encouraging and guiding newcomers. The clean and well structured code makes it a great learning resource. Thinking of using Hapi or Express for your new app development project? We are here to help you...

Contact Us Today!

Free Whitepaper: 5 Common Mistakes Managers Make in Choosing an App Development Company

SHARE THIS BLOG ON

Other Posts

STAY UP-TO-DATE WITH US

Subscribe to our newsletter and know all that’s happening at Cabot.

SHARE