Adding Routes to Hapi js server

aishadeshmukh
2 min readFeb 5, 2021

Check out my previous blog to set up the Hapi js server.

Now, we’ll add route to our index.js file.

server.route({
method: 'GET',
path: '/',
handler: (request, h) => {

return 'Hello World!';
}
});

Here, the method can be GET, POST, PUT, DELETE, as per the requirement of the task. Handler function will execute on going to the specified path. This functions should always return a value, which can be any result, error or null.

The index.js file will now look like below.

'use strict';const Hapi = require('@hapi/hapi');const init = async () => {        const server = Hapi.server({
port: 8000,
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);
};});init();

Now, run the file using below command on the terminal

node index.js

You’ll see the terminal showing

Server running at: http://localhost:8000

Now, go to your browser and type the path you want to execute. Here, our path will be http://localhost:8000/

You’ll see the below screen.

This is the expected output. Likewise, we can execute different requests for performing specific tasks for any application.

This is part 3 of hapi js series. Check out part 1 and 2 for Introduction to hapi js and how to set up a hapi js server.

--

--