Create a Server in Hapi JS

“Node.js is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js’ package ecosystem, npm, is the largest ecosystem of open source libraries in the world.” — Node.js Official

Hapi JS

Hapi enables developers to focus on writing reusable application logic instead of spending time building infrastructure. — Hapi JS Officials

Introduction:

Like Express JS, Hapi JS is another framework of Node JS. Some of the plugins like good, inert, vision, swagger extend the power of this framework. Hapi JS is the second most popular framework of Node JS in present time after Express JS. The main aim of the developer is Separation of Concern. Hapi JS framework is best in Separation of Concern. Trust me Hapi JS is easy to maintain the complex code very efficiently. Some of most companies are using Hapi JS.

This article kick off the basic introduction of Hapi JS and its tools. Hapi JS and its plugin give a solid starting for developing the complex application. So, let’s start my favorite part (coding).


Create Server in Hapi JS:

In this article, we discuss how to create a server in Hapi JS and how to achieve all the task of which have done by any server like ping any specific port, serve the static file, server-side routing and many more.

If you want to create an HTTP server in Node JS without the use of any web framework, please read my article Create HTTP Server in Node JS.

This article is breakdown into following milestones :

  1. Create Project for Hapi JS.
  2. Installing Hapi JS.
  3. Create Server.
  4. Basic Routing.
  5. Serve Static Files.

Create Project for Hapi JS :

To create a project in any node js framework by the use of package.json . Like that in Hapi JS, we create a project by creating the package.json. To creating the project to Hapi JS application, create a folder and open that location in command prompt for windows or in a terminal for mac.

npm init

Some of few questions is asked by command prompt and main question is :

entry point :
Create package.json

Installing Hapi JS:

For installing Hapi JS, you need to install following things:

  1. Node JS
  2. NPM (Node Package Manager)

You install Hapi JS by below npm command:

npm install hapi --save
Installing Hapi JS by npm command

Creating Server in Hapi JS:

For creating a server in Hapi JS is not the difficult task. For creating server is done by following steps.

  1. Create a JS file with name server.js in root location of the project folder.
  2. Import hapi in your project by require command like below
const hapi = require('hapi');

3. Create server by hapi.server( ). It takes an object as the parameter. This object takes two key: value pair one is port and second is the host. In my code port has value is 3000 and host has value is localhost.

const server = hapi.server({    
port: 3000,
host: 'localhost'
});

4. After declaring the server variable, we declared a function to start Hapi server.

const bootUpServer = async () => {    
await server.start();
console.log(`Server is running at ${server.info.uri}`);
     process.on('unhandledRejection', (err) => {       
console.log(err);
process.exit(1);
})
}

In above function, we declare a function with async keyword, so that function always returns a promise. In the first line of this function declaration, using await keyword, stop the execution until the server is started. In this function, we handled the unhandledRejection by the callback function and exit the node process.

5. In the last step, we call this function.

bootUpServer();

6. Last step to run the server is

node server.js

or

nodemon server.js

The major difference between the node and nodemon command is that if you use node command you manually run the command each time after save or if you use nodemon command it detects the changes automatically after saving any file of the project.

In the below gist, you found all the code which are explained above step by step.

Server.js

Basic Routing in Hapi JS:

Routing is the most common task of any server. Main responsibility of any server is how an application is responding to the client request to specific endpoints like path, URI by specific HTTP methods like get, post, put, delete.

In the server side routing, each route has one route method, one route path or URI and one or more route handler functions.

In Hapi JS, routing is not a difficult task. Below code of snippet is the example of routing in Hapi JS.

Hapi Server with routing

For creating the route in Hapi, we call route () taking an object with a method, path, and handler. In above route, the method is GET, the path is ‘/aboutus’ and handler is the handler function which returns a response.

Screenshot of route on browser

Serving static file and content in Hapi JS :

In Hapi JS, all other tasks like serve the static file, add logger, use graphql or add authentication is done by registering the plugin with the server for a specific task. Like that, if we want to serve the static content in Hapi JS server, then we will register the inert plugin with server first. The inert plugin is used to serve the static page in Hapi server.

  1. First we add inert package in the package.json by below npm command:
npm install inert --save
Install inert plugin

This command downloads the inert plugin in your project and adds it in package.json

2. After that we require inert in the server.js by require command like below:

const inert = require('inert');

3. After that we need to update the bootUpServer function with below line of code of snippet

await server.register(inert);

4. In the last step, we create a route for rendering the HTML file on browser. For creating HTML file, we need to create a public folder in the root location of the project and creating HTML inside the public folder.

server.route({    
method: 'GET',
path: '/staticpage',
handler: (req, h) => {
return h.file('./public/static.html')
}
})
server.js

Conclusion:

Hapi has many, many other capabilities and only a select few are documented in article here.

This is my very first article on Hapi JS. Hope this is informative. Now I’m working on my next article “Enjoying API validation in Hapi JS with JOI”. I’m coming with this article as soon as possible.