Hapi is one of the major Node.js frameworks that is popular among web developers. It is an open source framework that can build a scalable and powerful web application. Hapi helps developers to focus on writing reusable application logic instead of spending time building infrastructure. Historically, Eran Hammer who led Walmart Lab created Hapi to handle traffic Walmart’s Black Friday. Today, we’ll be showing you how to set up a basic server and display “Hello World!” in your browser by using hapi.
Firstly, we need to create a new directory for the project and install hapi in that directory. In your terminal, run the following command below to get started:
# Create a new directory for the project $ mkdir project-hapi && cd project-hapi # Initialise a new Node project $ npm -y init # Install hapi.js $ npm install @hapi/hapi # Create a new server file $ touch index.js
Next, navigate to the index.js file in your directory and write the code below in the index.js to create the server:
'use strict'; const Hapi = require('@hapi/hapi'); const init = async () => { const server = Hapi.server({ port: 3000, host: 'localhost' }); await server.start(); console.log('Server running on %s', server.info.uri); }; process.on('unhandledRejection', (err) => { console.log(err); process.exit(1); }); init();
Your terminal should display “Server running on http://localhost:3000” when you run command “node index.js” on the terminal.
To display “Hello world!” on the browser, you need to add a route method in the index.js. Please write additional line codes:
'use strict'; const Hapi = require('@hapi/hapi'); const init = async () => { const server = Hapi.server({ port: 3000, host: 'localhost' }); //the additional line 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();
After write the additional line of codes, you run again the server by running command “node index.js” on the terminal. Currently, you’ll see the text ‘Hello, World!’ if you visit http://localhost:3000.
This tutorial is just an intro for beginners. There are still a lot of concepts that are not mentioned in this tutorial such as authentication, plugging, testing and more. Thank you for reading and stay tuned for more tutorials.