Introduction to Hapi.Js
hapi.js (also known as hapi) is an open-source framework for web applications. The most common use of hapi is to build web services such as JSON API. You can build application programming interface (API) servers, websites, and HTTP proxy applications with hapi.js.
hapi was created by the mobile team at Walmart Labs—led by Eran Hammer, who created OAuth—to handle their traffic for events like Black Friday, one of the busiest days for online shopping in the U.S. calendar.
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.
I started using Express to build my web apps. I was working on small projects, and Express is well-suited for small projects. But as I began to work on larger, more complex projects, I kept running into problems with the framework. It is tough to do scaling in Express. There’s no single recommended way of organizing things in Express, which can be a trap for beginners and experienced developers alike, and can result in unmaintainable projects.
Walmart has a lot of users, and their systems are complicated. You could do enterprise-scale apps successfully in hapi. The transition to using hapi for me was quick and painless. I liked the simple configuration-driven APIs and the powerful plugin system of hapi.js.
hapi is important for developers to understand because it’s designed to let them focus their time on critical project tasks instead of building infrastructure. We’re going to take a deep dive into why hapi is a good thing for you to know about. Then I’m going to walk you through exactly how to use hapi.
Who is using hapi.js?
There is a huge community of companies using hapi. According to hapi, the companies that appear below are some of the major players using their framework.
Some of the hapi users are saying:
“hapi is the solid foundation powering our open source npm proxy that has served millions of requests without issue. With a solid plugin architecture, hapi has proven the ideal choice for some of our frequently changing internal tools.”
– Jean-Charles Sisk, Engineering Architect at PayPal
“hapi has all the latest security and robustness features built in that production sites need. We love using, supporting, and creating open source software that benefits the entire community and we appreciate the enormous effort and dedication of the hapi team.”
– Danny Coates at Mozilla
Why should you use hapi?
hapi provides a robust plugin system that allows you to add new features and fix bugs at a fast pace. hapi enables you to build scalable APIs. It is an excellent choice for building Representational State Transfer (REST) APIs because it provides you with routing, input, output validation, and caching. You can build an API that serves all kinds of clients that need mobile and single-page applications.
You can also use MySQL, MongoDB, and Postgres with hapi.js. hapi also allows you to build static websites. It provides a templating engine to render the dynamic content. You can use hapi.js with any front-end framework, like React, Angular, and Vue.js to create a single-page application.
hapi is also a good choice for building proxies. For example, Walmart is using hapi to forward requests from its API to external Java services. If you want to build a single-page application and you have multiple back-end servers, even if they are on the same host as the web app but on different ports, you run into cross-origin resource sharing issues. You can solve these issues with the help of a proxy.
hapi works well with social apps and real-time chat applications. You don’t need to create your own custom plugin for real-time applications, because hapi provides a plugin called nes for real-time chat applications.
hapi as an API Server
hapi has simplified the way in which you can write highly scalable APIs. It is powerful and features a rich framework with a robust architecture. Here is the architecture of the hapi API server:
A client or browser will send the network request to the hapi application. The browser will send the HTTP request for the products. hapi will receive the HTTP GET request and find the products from the database, and then a client will receive the array of products.
hapi as a Website Server
You can also build a website server application with hapi. Your client or browser will send the request for index.html to hapi, which will have a templating engine like EJS or Jade. These templating engines render the dynamic content in HTML. After finishing rendering in HTML, hapi will send the index.html to the browser.
hapi as an HTTP Proxy
Another use for hapi is as an HTTP proxy. Walmart uses hapi as a proxy HTTP service; while the majority of the business service is still served from the Java external service, all the incoming traffic is sent through a proxy server.
Big Picture of a hapi Application
Here are the steps involved to fetch data from a hapi application:
- The browser sends the request for the products. A request is received by the node and forwarded to hapi.
- The hapi application authenticates users, and runs the appropriate route handler for the current route.
- Your application gets data from the database.
- Product data is given to the hapi reply function.
- An HTTP response is sent from the node to the cloud application.
If you’re looking for a flexible framework to build all types of webpages and applications, hapi is something you should learn more about.
The Building Blocks of hapi.js
hapi is made up of several key components. The server is the main container of the hapi application. You use the connection to attach a hapi server to the network interface so it can start accepting the incoming request. You can also connect a hapi server to multiple ports such as 3000 and 3001.
Make sure you specify your HTTP request type like GET, POST, PUT, DELETE, or PATCH. You must specify the path for each route. Each route will have a handler function, which you must define while creating a new route. Whenever you send the request to any endpoint, the router handler function will be called for this path.
Plugins are a handy feature of hapi. You can add more functionalities to a hapi application with the help of plugins. If you want to connect to the MySQL database, hapi has the Sequelize plugin. You can use the hapi-mongoose plugin to communicate with MongoDB.
Creating a New Server
You can create a new server by creating a new instance of hap.Server()
Open the empty project into your code editor and run this command:
It will create the new package.json file. Now you need to install the hapi framework.
Create a new file called server.js in the root directory.
Now you can run the hapi application by running this command:
You will see this message: Server Running at PORT 3000.
Creating New Routes
hapi provides a server.route method to create new routes in hapi.
server.route will take an options object, which will have three properties. You need to specify the path for the endpoint. Make sure you define the method as GET, POST, PUT, DELETE, or PATCH.
The last property is the handler function. When you send an HTTP request to any route, hapi will call the handler function and it will take two arguments, req and reply. You can get all the request data from the req object. You use the reply method to send a response from the server.
You have to run the application by using node server.js. You can test these two routes by sending a request from the browser.
Adding Plugins in hapi.js
You can extend the server by adding plugins to a hapi application. You can also convert a hapi application into modules by using plugins.
You have to use server.register() to register the plugin. This server.register() can take an object or an array of configurations. I have registered the good plugin in hapi.js. It is used for the logging purpose in hapi. This configuration object must have the register property and options is the optional property.
If a plugin requires any options, you can also include options during the plugin configuration. I use reporters inside the plugin options. Reporters are used for logging the response.
The Right Framework
Because hapi.js is a web application framework that helps you build websites, APIs, or just about any HTTP service, it is an incredibly useful tool.
The main building blocks of hapi apps are servers, connections, routes, handlers, and plugins. hapi works because you can customize these building blocks, and make the framework fit your requirements and needs. It also lets you build your apps in a modular way by making use of its robust plugin system and npm package manager.
Using hapi can make your development projects easier, and let you focus more on the critical parts of your build, rather than worrying about the infrastructure details.