An Insight into the Technology world.
Analysis and Insight from Savvycom Team.

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!

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

Brief

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:

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.

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.

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.


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

Keep reading!

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.

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();
});

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

“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”:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

For every other path, the server will respond with 404 Not Found.

Hapi

The following example is the most basic hello world app using Hapi:

'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();

Then you just launch the application by running npm start and open localhost: 8000/hello in your browser.

Koa

This is the most basic example of a “Hello World!” app on Koa that listens on the port 3000.

const Koa = require('koa');
const app = new Koa();

app.use(async ctx => {
ctx.body = 'Hello World';
});

app.listen(3000);

For every other path, the server will respond with 404 Not Found.

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:

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

Hapi

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

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

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

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

  • 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:

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

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:

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

Community

The community involvement is also a good indicator for the position of the framework on the market.

Wanna know how many contributors there are in each framework?

Keep reading!

Express

  • Number of contributors: 220
  • Closed Pull Requests: 821

The Express community meets regularly, and they communicate through their mailing list, Gitter, IRC channel, issues in GitHub, and the Express Wiki.

Finally, express is probably the most popular framework for Node.js, and there are many other popular frameworks that are built on Express.

Hapi

  • Number of contributors: 184
  • Closed Pull Requests: 1176

You can join the slack channel: hapihour.slack.com, visit the community page, community governance page and follow them on Twitter to keep updated with the latest news.

Koa

  • Number of contributors: 169
  • Closed Pull Requests: 577

The community involvement is also a good indicator for the position of the framework on the market.

You can join G+ koa Community, mailing list, contribute to Koa’s repo, join koa slack or start a discussion in hashnode.

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.

Be right there cause’ this is apparently the most useful key-takeaway in this blog!

Express

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

  • 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.

Hapi

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

  • Advantages

Hapi is Node.js framework with a powerful provided plugin system, therefore developers can add new features or fix bugs at a fast pace. As well as that, Hapi can assist you to manage the whole development process easier.

As Hapi allows developers to have deeper control over request handling, building large scale or enterprise-sized applications is a piece of cake.

On top of that, as this framework is based on configuration rather than code, Hapi adds consistency and reusability to the developing process.

  • Disadvantages

Apart from being a useful tool in creating customized construction blocks, Hapi does have a considerable minus.

This framework relies heavily on manual labour, which means you’re on your own to figure out how to use them.

There are a lot fewer samples or open-source applications that use Hapi, so the project may involve developers more than when using third-party middleware.

  • Recommendation

As Hapi is tailored towards big and complex web applications, if you’re in the process of building one app like that, you should definitely go for this framework.

With the back-up of WalmartLabs and many other large companies that have already used Hapi, you can rest assured that this web framework has been tested and ready for any heavy tasks.

Koa

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

  • Advantages

By taking advantage of ES6 generator feature, using Koa will help you avoid callbacks and build web applications with great performance.

Besides, it makes the coding management process easier. Hence, you can easily handle errors faster.

Moreover, with just over 500 lines of code, Koa is an extremely lightweight framework, making it a special point of this tool.

Overall, Koa brings a faster and easier experience when picking (or writing) middleware for first-timers, rather than compromising with middleware like Express or Hapi.

  • Disadvantages

Despite its pros, Koa still presents some hindrances. As it is the newest out of three frameworks (Express, Koa and Hapi), the open-source community revolving around Koa is relatively small. Therefore, it suffers a shortage of support from its web framework community.

In addition, Koa is still unstable. Using the ES6 generator, which is way above of the game, means that Koa framework is not compatible with any types of Node.js framework middleware existed.

  • Recommendation

As Koa is a lightweight and modular framework, you can create a web application from scratch, upon request and without tonnes of unwanted materials.


Conclusion

There is no “best” framework among Express, Hapi and Koa. They are equally distinctive, remarkably unique and constantly innovative while keeping the nature of Node.js as being light-weight, scalable and performant. They are all excellent framework, in their own different ways.

That being said,  it’s a battle with all three of them co-awarding the first prize, with each of them comes with both pros and cons, advantage and drawbacks as well as various distinctions in core competency, basic setup, middleware, installation and community.

What really matters is you choose “the one” for your business – the framework that matches your products, your business goals, strategy and organisation. Otherwise, it means nothing even if you pick out the most popular or the fastest performing one.

To do that, you shall:

  • Make a list of core traits of your business (such as your company structure, business goals, development strategy, product competency, target market, etc).
  • Read carefully the above information to pinpoint the nature of each framework, which can be optimised by the below bullet points:
  • Express: Lightweight and minimalist, supported by most middleware, seems to be the defacto standard.
  • Koa: Great async/await support for asynchronous flow. Seems to be ‘the new hotness’.
  • Hapi: Great for larger-scale projects out of the box, but has some extra middleware to deal with.
  • Analyse the information about your company in comparison with those above bullet points to strategically decide on the most suitable for your business. Remember, just because it is popular doesn’t mean it is going to make you “happy” – sometimes a “less impressive” one is all you need for a long, healthy relationship.

Make sure you fully understand the differences and carefully collate your business to it, so that you won’t regret choosing a dull one later!

If you are still confused about which framework you shall apply for the best business efficiency, feel free to contact us for professional consultations! We would be happy to help you make a leap in the industry.

Contact us via:

  • Phone: +84 24 3202 9222
  • Hotline: +84326752886
  • Email: contact@savvycomsoftware.com

Talk to An Expert

Leave a Reply