How to set up a Hapi.js project and create your first route?

Khouloud Khezami
3 min readDec 6, 2020

--

Hapi.js logo

Hapi.js is basically an abstraction layer on top of Node.js which makes it easier to create restful APIs with it.

In this Tutorial we will create a simple REST API with Hapi.js. We will start by setting up a project and adding all the dependencies needed, then setup the databases and create some fake data, and finally create the CRUD routes.

Ready? Let’s jump right into it then.

First things first, open your cmd and locate yourself where you want to create your new project.

create a folder for your project with mkdir test-hapijs

Go inside your folder with cd test-hapijs

& now initialize your project with npm init -y

This will allow us to install the following packages we need for this tutorial.

npm i @hapi/hapi reflect-metadata sqlite3 typeorm

since we are using typescript, we should also add the types for the libraries we have just installed, therefore run this command as well:

npm i @types/hapi @types/node ts-node-dev typescript -D

The ts-node-dev dependency will allow us to run our code as well as recompiling and re-running our code every time we make a change in our typescript files.

All good? Let’s get started. Open your project with your fav editor. (I personally use VSC)

In order to be able to run our typescript files we should add the following line “ts-node-dev”: “ts-node-dev” to our package.json under scripts.

Once you are done, create index.ts in your root folder.

Now we should go to the index.ts file and write an init function to create a server and run the code. To do so, please follow the following steps:

Don’t forget to call the init function at the end.

To Run the project, open your terminal and paste:

npm run ts-node-dev index.ts

Result

Hallelujah, you are all set up!

Now, let’s define our first hello world route!

To create a route we should do as follow:

The route should always receive an object that contains the HTTP method and a path. The handler is the function that will be executed when the path is called.

If you open your Postman & try calling the route you will definitely have this result.

This is the first part of the Hapi.js series.

I hope that it was a clear and straight forward explanation, please let me know if you have any questions at info@techsoupe.com

instagram: https://www.instagram.com/techsoupe/

--

--

Khouloud Khezami
Khouloud Khezami

Written by Khouloud Khezami

Software Engineering/ Business Informatics student.

No responses yet