Express vs. Hapi: A Head-to-Head Comparison
Express vs. Hapi: A Head-to-Head Comparison
Express and Hapi are frameworks based on Node.js, an open-source server environment that runs on various platforms, using JavaScript as the language of choice. Since both frameworks are Nodejs-based and popularly used for web and mobile application development, let’s compare them and see which is more suitable for your needs as a developer.
An Overview of Express
Express is a minimal, fast, and un-opinionated web framework for Node.js. It is used specifically for back-end web application development and is known as the “de facto standard server framework” for Node.js.
Express is heavily dependent on code but allows you to build lightweight and consistent APIs. It offers a minimal and flexible framework that delivers a myriad of features for web and mobile applications. Furthermore, it has several HTTP utility methods and middleware for developers to create robust APIs simply and efficiently. Some popular frameworks built on top of Express are – ItemsAPI, Feathers, LoopBack, and Blueprint.
Here are some of the primary features provided by Express –
- Robust routing
- High performance
- Super high test coverage
- HTTP helper support
- View system supporting 14+ template engines
- Content negotiation
- Support for application generation through executables
Express’ key focus is on being minimal, fast, and simplistic. This is perhaps what makes it one of the most popular Node.js frameworks used.
Advantages
- Using a single language (Javascript) for writing both backend and frontend applications makes Express highly developer-friendly.
- Easy to install and set up; is known for having an easy learning curve.
- Express has middleware functionalities built-in to handle and support error handling in both synchronous and asynchronous codes.
- Thanks to its extensive developer community, there will be no limitation in the availability of third-party plugins and tools.
- Express is also famous for its scalability and is a good choice for businesses dealing with thousands of daily users.
- Express is non-opinionated and therefore imposes no real constraints on developers for how they structure their applications.
Disadvantages
- Too much flexibility: lack of constraints on the developer can let through suboptimal development practices and vulnerabilities in your application.
- One can find the manual endpoint creation aspect of Express laborious. Additionally, refactoring becomes difficult as the codebase starts to increase in size.
- For those developers not familiar with the middleware functions, working on Express can become tricky and take time to learn.
Popular Use Cases
You’ll find Express most commonly used across –
- Single-page applications
- Reusable application modules
- Middleware applications
- RESTful APIs
- Enterprise web applications
- eCommerce web applications
Express is extremely popular and powers applications for about 1609 companies. Here are some popular ones –
- IBM
- Uber
- MuleSoft
- NodeBB
- Accenture
- Fox Sports
Hello World
Now let’s look at what a classic Hello World application in Express looks like –
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 at http://localhost:${port}`)
})
Output:
An Overview of Hapi
Hapi helps developers build robust, scalable applications with a focus on creative functionality and minimizing overhead. It encourages developers to design their code and take ownership of it. Hapi is short for Http-API and pronounced ‘happy.’
It is open-sourced like Express and developed by Walmart Labs (believe it or not) to handle high-traffic events such as Black Friday. Walmart initially went with Express.js, but when it did not suit their requirements, Hapi emerged as a standalone framework for Node.js. As a result, Hapi served Walmart’s mobile traffic during 2013’s Black Friday.
Hapi is known as the largest deployment of Node to date. It is rich with different features, and unlike Express’s focus on code, Hapi focuses more on configuration.
Here are some of its features –
- A secure and simple framework for developers to trust, using a rich ecosystem and advanced features
- High code readability, coverage, and fewer unresolved issues and pull requests (currently, only one open issue and 19 pull requests on GitHub).
- Clean and easy to learn interface allows users to build applications according to their requirements
- True extensibility and customization with safety and predictability
Advantages
- Robust and ever-evolving plugins library; supports rapid development.
- A lot of pre-built tools for supporting authentication and authorization with APIs
- It boasts a secure framework. Error messages that could potentially leak data are blocked immediately. It will also stop messages that echo back unsecured loopholes.
- With the help of continuous caching, Hapi can improve the performance of the web application.
- You can use it to make REST APIs. Hapi supports routing, input, output validation, and caching.
Disadvantages
- Developers often have to figure out how to structure their code themselves. This can be a bit tough to work around for beginners without involving a lot of hit-and-trial.
- Developers need to create endpoints and test them manually.
- Compatibility issues: many of the plugins and modules are restrictive and only Hapi-specific. When this happens, developers cannot work additionally with other frameworks.
Popular Use Cases
You’ll find Hapi most commonly used across –
- Network applications
- Single Page Application (SPA) servers
- HTTP-based software applications
- eCommerce web applications
- JSON APIs
Hapi, in contrast to Express, is only used by applications of 74 companies currently. Regardless, here are some of the popular ones:
- Alphamantis
- Modulus
- Beats Music
- GetHuman
- Octovis
- Liaison
Here are other projects built using Hapi:
- Colonizers - a HTML5 multiplayer game
- MasteryJS - a scalable API server
- Paydash - MGNREGA’s worker payment dashboard
- Postmile - collaborative list making tool
Hello World
Here is an example of a Hello World application in Hapi:
'use strict’; const Hapi = require('@hapi/hapi'); const init = async () => { const server = Hapi.server({ port: 3000, host: 'localhost' }); server.route({ method: 'GET', path: '/', handler: (request, h) => { return 'Hello World!'; } }); await server.start(); console.log('Server running on %s', server.info.uri); }; process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); init();
Express vs. Hapi: Side by Side Comparison
Now let's do a side-by-side comparison of Express and Hapi based on various aspects like popularity, speed and performance, installation ease, security, architecture, documentation, etc.
Popularity
Here are some statistics from both frameworks based on their Github projects.
Express |
Hapi |
|
Github Stars |
53.8k |
13.4k |
Users |
10.2m |
21.6k |
Contributors |
262 |
209 |
Forks |
9.1k |
1.3k |
Repositories |
41 |
67 |
As you can see, Express has more stars and users at the moment as compared to Hapi. Popularity is an essential factor to consider because it helps determine the breadth of support and the community available. From a development support perspective, Express has won the contest here.
Speed and Performance
According to this synthetic Hello World benchmark by Fastify, Express was able to process 8733 requests per second using its Hello World example. For the same test Hapi showed greater than 2x better performance, processing 18915 requests per second.
Even though these comparisons are from basic Hello World applications (there’s much more you can optimize for your custom applications), Hapi indicates a reasonable edge over its counterpart.
Installation
Both Express and Hapi are easy to install and set up. They both require you to have Node.js installed on your system for further installing and running the web frameworks. You can find installation instructions to Express and Hapi in the attached links.
Security
Security is an aspect that haunts developers. Both Express and Hapi handle security differently.
For Express, it is crucial to keep in mind Node.js’s reliance on Express. If there are any weaknesses in Node.js, they are bound to impact Express. Yet, it’s not like Express hasn’t done anything about it. It regularly makes security updates which you can find here. In addition to the security updates, it also has an extensive security best practice compilation for developers. Here are some of the best practices to follow:
- Use the latest versions of Express
- Ensure the use of Transport Layer Security (TLS)
- Use Helmet middleware
- Securely use cookies
- Prevent attacks against authorization by ensuring login endpoints are protected to secure data.
- Dependencies should be secure.
Hapi ensures that security is a priority through the following factors:
- Ensuring and requiring the most secure settings for management, control, and distribution of code for all the contributors
- Hapi components come with secure defaults and are updated regularly
- Integrating authorization and authentication in the architecture
- Using features such as encrypted and signed cookies, secret rotation, and HTTP security headers
Architecture
Express does not endorse a specific architecture, giving developers the freedom to organize their applications in their own way. The most preferred architecture type, however, representing Express apps is the Model-View-Controller (MVC).
Hapi, on the other hand, is more plugin-centric. It mainly supports the configuration-based MVC architecture and uses plugins to configure runtime through code. Hapi plugins can route, authenticate, log, and do much more.
Express is less opinionated than Hapi, making it more abstract. While both frameworks can be extensible and adaptable, they can provide the same functionalities through different architectures.
Documentation and Support
Both Express and Hapi have a vast resource pool to support developers.
Express’s website is minimal but offers excellent documentation. From its ‘getting started’ tab to its resources and tutorials, Express has it all. If the website is not good enough, the extensive community is out there to help you too.
Hapi also does an excellent job at documentation. It’s helpful, especially for beginners, from a detailed front page about its features to the detailed set of tutorials. While it does have a relatively small community, the information on the website covers it for the most part for now.
Community
Access to a community is vital for developers, especially for open-sourced frameworks. This provides technical support and also gives a sense of credibility for the framework. If there are issues or questions, developers can quickly get responses and discuss solutions with fellow developers. The following shows how both frameworks fare across different online platforms.
Express |
Hapi |
|
Website |
||
Github |
(48 organization members currently) |
(5 organization members currently) |
NPM Downloads |
~16.64m Weekly Downloads |
~ 385k Weekly Downloads |
StackOverflow |
~81k questions |
~1.2k questions |
|
Not very active; last post was in September 2020 |
Active; last post was on 11 July 2021 |
Slack |
N/A |
|
Youtube |
N/A |
It’s also important to note the number of contributors to both projects. As of right now, Express has 262 contributors, while Hapi has 209. Developers can also apply to be contributors through their respective websites as well. To conclude, Express has more resources and a larger community than Hapi to support many developers for a quick fix. But it is not as active as Hapi on Twitter.
Hapi or Express - Which is Best for Your Needs?
In this article, we battled two of the most talked-about Node.js frameworks, Express and Hapi. Both are strong open-sourced contenders. There is no best framework to be crowned. Both can handle specific situations differently, and you must know what you’re looking for in a framework before working with them.
Express is a fan-favorite for small and middle-sized projects. If your project does not require a lot of complexity, it is the best choice for its simplicity and minimalism. It is not opinionated, easy to learn for beginners, offers support from an enormous developer community, and excellent documentation.
Hapi, on the other hand, is recommended for large and complex web applications. It emerged to address the limitations of Express by Walmart’s tech team to handle the busiest online shopping event on the calendar – Black Friday. Had it not outperformed Express so clearly (even on the benchmarks we discussed above), it would not be where it is right now.
Now that you have a good understanding of both these frameworks go ahead and pick one that best suits your application’s and your organization’s interests.
Happy coding!