The Best Node.js Framework: Koa VS Express VS Hapi [Detailed Comparison]

Savvycom JSC
Savvycom
Published in
10 min readMar 8, 2021

Since its launch in 2009, Node.js has become one of the fastest-growing open-source, cross-platform Javascript run-time environment and therefore, many Node.js web frameworks were created. Each framework is catered to the demands of users and developers, such as to improve productivity, scalability, enhance the speed of applications and performance capability. With the advantages of being lightweight, scalable and many others, no wonder Node.js web frameworks are rapidly gaining attention and becoming the go-to option for developers at the present.

In this article, we will introduce the three most popular web frameworks in Node.js (Express, Koa and Hapi) and how to differentiate them to pick the right one for your project.

Today you’ll learn:

  • Full faces of Express, Hapi and Koa frameworks.
  • The differences among them.
  • Why they form a squad of biggest popularity.
  • The best framework for your business strategy.

Heat up yet? Let’s start the learning journey!

1. What are Express, Hapi and Koa?

To keep you from dropping dead before the mind-boggling information later in this blog, I’ll flash through the basics of each of the 3 frameworks as following:

1.1. Express

Express is a code-centric web application framework that aims to provide developers with a simple, performant, and unopinionated toolset for creating web application servers. The API is kept lightweight and maintains a high degree of consistency with the NodeJS core API. Because of its minimalist nature, many common tasks require outside modules.

Having been in development since 2009, Express is a mature project with a strong community backing. With +43000 stars on GitHub and about 8 millions npm weekly download, Express has proved its reign as the most loved and widely used Node.js web application framework. The latest version of Express is 4.17.1 published in May 2019. The publisher also announced on its 5.0 version, which is currently in the alpha stage, promising the upcoming dawn of Express 5 universe.

1.2. Hapi

Hapi is a feature-rich framework that favours configuration over code and attempts to cover a wider range of use cases out of the box. It was originally created by a member of WalmartLabs, and it is intended for large teams and large projects. Because of this, it can be a bit boilerplate-heavy for small projects.

While Hapi is less widely used and slightly newer than Express (Hapi started development in 2011), Hapi is used by a variety of large companies such as Walmart, Disney, and Macy’s. It has more than 11000 stars on GitHub and over 250000 npm downloads each week.

1.3. Koa

Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly increase error-handling.

Koa does not bundle any middleware within its core, and it provides an elegant suite of methods that make writing servers fast and enjoyable. It scores quite impressive stars on GitHub: +25000, earning approximately 300000 npm weekly downloads as of today despite its being one of the newborns in the Node.js game.

2. KOA vs EXPRESS vs HAPI: A Detailed Comparison

Let’s differentiate the three most popular Node.js frameworks to find which is the best for your project. Here are some of the criteria that we think you should take into consideration:

  • Basic Setup
  • Middleware
  • Installation
  • Performance
  • PROs and CONs
  • Community

2.1. Basic Setup

Here comes the start of the complicated part. Because Express, Happi and Koa are all unique in each’s own way, with several distinctive traits and functionalities. The basic set up is not an exception. To start off, let’s make a new server, tell it to start listening to port 3000, and have it log a message when it has done so.

Express

The basic setup in Express is pretty straightforward. The express module returns a function (with some helper methods attached) which will return a new Express app. The return value of app.listen is an instance of HTTP.server.

Just look at these codes as an example:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
console.log(`Express is listening to http://localhost:${PORT}`);
});

Hapi

The basic setup for Hapi looks very similar to that of Express, although Hapi’s focus on configuration over code is already beginning to make an appearance. After instantiating a new Hapi server, we add a connection, providing it with the port via a configuration object. Then, we simply start the server.

For example:

const Hapi = require('hapi');
const PORT = process.env.PORT || 3000;
const server = new Hapi.Server(PORT);
server.start(() => {
console.log(`Hapi is listening to http://localhost:${PORT}`);
});

Koa

Because Koa was given birth by the same team as Express, the basic setup of those two can be quite confusing at first glance.

const koa = require('koa');
const app = koa();
const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, () => {
console.log(`Koa is listening to http://localhost:${PORT}`);
});

Right away you can see the similarities., but essentially you just required Koa instead of Express. We even have the same app.listen() wrapper function. Still, what makes Koa really separates from Express, as introduced in the first part, is its way to ditch callback completely by either using ES6 function generators or the newer async/await control flow. It also eliminates much of the middleware that Express uses, which at some points become even more dominant than Express.

2.2. Middleware

One of the major concepts Node developers are used to is working with middleware. Middleware functions are functions that sit in between requests and responses. They have access to the request and response objects and can run the next middleware after they’re processed.

To understand the competency of each, let’s take a look at how they’re defined in the different frameworks by implementing a simple function that logs the time a request is made to the server.

Express

Registering middleware in Express is as simple as binding the middleware to the app object by using the app.use() function.

For instance:

app.use((req, res, next) => {
console.log(`Time: ${Date.now()}`);
next();
})

Hapi

In Hapi there are certain extension points in the request lifecyle. The server.ext() method registers an extension function to be called at a certain point in the request life cycle.

We make use of the onRequest extension point in the example below to register a middleware (or extension) function:

server.ext('onRequest', (request, h) => {
console.log(`Time: ${Date.now()}`);
return h.continue;
});

Koa

Middleware registration in Koa is similar to Express. The major differences are that the context object (ctx) is used in place of the request and response objects in Express and Koa embraces the modern async/await paradigm for defining the middleware function.

Take this as an example:

app.use(async (ctx, next) => {
console.log(`Time: ${Date.now()}`);
await next();
});

2.3. Installation

The installations of Express, Koa and Hapi are also differentiated as below:

Express

For installing Express, you need to have already installed Node.js. If you want to install Express in a specific directory and save it in the dependencies list:

$ npm install express --save

However, if you want to install Express temporarily and not add it to the dependencies list, you can use:

$ npm install express --no-save

Hapi

To install Hapi, you need to have Node.js installed and then:

$npm install Hapi

to save it to your package.js on dependencies.

Koa

Koa requires node v7.6.0 or higher for ES2015 and async function support. You need to have already installed Node.js. You can quickly install a supported version of Node.js with your favourite version manager:

$ nvm install 7
$ npm i koa
$ node my-koa-app.js

2.4. The “Hello World” Example

To dig even deeper, let’s take a “Hello World!” example, put it as listening on port 3000 and responds “Hello World”.

Express

This is the most basic example of how to create an express app that listens on port 3000 and responds “Hello World”. For every other path, the server will respond with 404 Not Found.

const express = require('express')
const app = express()
const port = 3000app.get('/', (req, res) => res.send('Hello World!'))app.listen(port, () => console.log(`Example app listening on port ${port}!`))

Hapi

The following example is the most basic hello world app using Hapi. Then you just launch the application by running npm start and open localhost: 8000/hello in your browser.

'use strict';const Hapi=require('hapi');

// Create a server with a host and port
const server=Hapi.server({
host:'localhost',
port:8000
});

// Add the route
server.route({
method:'GET',
path:'/hello',
handler:function(request,h) {

return'hello world';
}
});

// Start the server
const start = async function() {

try {
await server.start();
}
catch (err) {
console.log(err);
process.exit(1);
}

console.log('Server running at:', server.info.uri);
};

start();

Koa

This is the most basic example of a “Hello World!” app on Koa that listens on the port 3000. For every other path, the server will respond with 404 Not Found.

const Koa = require('koa');
const app = new Koa();app.use(async ctx => {
ctx.body = 'Hello World';
});app.listen(3000);

2.5. Performance

The performance is, for the most parts, one of the most important parameters for you to evaluate its quality as well as the suitability of it to your business model. In this part, we are going to elaborate on the performance of each of them so that you could have a thought on the framework you think the best you should choose.

Express

Express provides a thin layer of fundamental web application features, without obscuring Node.js features that are familiar.

The best practices for improving express performance includes:

  • Use gzip compression.
  • Don’t use synchronous functions.
  • Do logging correctly (for debugging, use a special module like debug, for app activity use winston or bunyan).
  • Handle exceptions properly, using try-catch or promises.
  • Ensure your app automatically restarts by using a process manager or use an init system like systemd or upstart.
  • Run your app in a cluster. You can increase the performance of a Node.js app greatly by launching a cluster of processes (a cluster runs multiple instances of the app, distributing the load and tasks among the instances).
  • Cache request results, so that your app does not repeat the operation to serve the same request repeatedly.
  • Use a load balancer to run multiple instances of it and distribute the traffic, like Nginx or HAProxy.
  • Use a reverse proxy that performs supporting operations on the requests. It can handle error pages, compression, caching, serving files, and load balancing among other things.

A simple “Hello World” app has the following performance request per second:

Maybe You Like To Know: 10 major mistakes when developing on Node.js

Hapi

A 2017 study on Node.js frameworks, showed that Hapi performed the worst compared to the other frameworks.

As we can see in the following graph compared to Express.

  • Express continues to maintain a performance edge over Hapi.
  • Applications with significant performance requirements should consider the advantage Express has over Hapi.

A simple “Hello World” app has the following performance request per second:

Koa

With Koa, you can build web apps with great performance. This is because you can stop using callbacks, deal with errors faster, and because Koa itself is a very lightweight framework. As well as that, it makes the code management process easier.

It’s important to take into account the best practices for having a better performance in Node.js like running things in parallel, use asynchronous APIs in your code, keeping code small and light, and using gzip compression.

A simple “Hello World” app has the following performance request per second:

READ MORE: How to Hire the Best Node.js Developers: The Ultimate Guide

2.6. Pros & Cons of Each Framework

Understanding that you might be tired after reading the wall of text I’ve just written above and because it is too long of information for you to swallow, you probably missed out somewhere; I will summarise the upper and lower hands of each so that you’re easier to compare among three of them.

Express

  • Advantages

Express has the biggest community of users out of all existed web application frameworks for Node.js, with a history of over 9 years of development behind it. Many of its members praise that Express is a good and powerful tool, and it does do a good job.

Because of its simplicity, Express is very user-friendly and can be applied successfully by inexperienced people. It also helps simplify the testing process and improve application performance.

Despite that, with a powerful rooted API, various tasks can be performed including building an Express RESTful API server and routes for simple web applications. Additionally, it’s extremely easy to integrate with third-party services and middleware as Express makes use of the Node.js manager package node.

  • Disadvantages

While it is a convenient and easy-to-use tool, Express does have some drawbacks. One of those is the lack of a recommended method of organisation, which can be a problem for developers as they’re unable to repair the projects if needed.

Therefore, it is important to be very clear about the approach when maintaining the code. Furthermore, Express required a lot of manual labour-intensive tasks since you need to create all endpoints. Unless it’s handled professionally, the problem can affect a great deal to your memory usage.

  • Recommendation

For small and middle-size projects, Express would be a suitable option. Some of the examples that can be named are MySpace, PayPal and Klout sites, which all use the Express web framework as a middleware framework.

However, if you’re going to develop a complex project with a large development team, Express may not be the best tool to use.

This is a brief summary of an article published on Savvycom blog. If you would like to learn more detailed information, feel free to read the full article.

--

--

Savvycom JSC
Savvycom
Editor for

Leading Digital Transformation and IT Service Provider in SEA