Getting Started with Hapi.js for Server-Side Development
Written on
Chapter 1: Introduction to Hapi.js
Hapi.js is a minimalistic framework for Node.js designed for building backend web applications. In this article, we will explore the steps to create backend applications using Hapi.js.
Section 1.1: Setting Up Your Project
To kick off, create a project directory, navigate into it, and execute the following command to install Hapi.js:
npm install @hapi/hapi
This command will download the Hapi.js package, which is essential for our application.
Subsection 1.1.1: Creating a Simple Server
Next, we can set up a basic backend application by writing the following code:
const Hapi = require('@hapi/hapi');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: '0.0.0.0'
});
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();
In this snippet, we start by importing the Hapi package. We then create a server instance using the Hapi.server method. The host is set to '0.0.0.0' to allow incoming requests from any IP address. We define a route using server.route, specifying the HTTP method, path, and the function that handles requests. Finally, the server is initiated with server.start(), and an error handler is added to manage any unhandled rejections.
The video titled "Hapi.js Framework Crash Course" provides a comprehensive introduction to setting up a Hapi.js application, covering the essentials needed for development.
Section 1.2: Implementing Authentication
Adding authentication to our application is straightforward. Below is a sample implementation:
const Bcrypt = require('bcrypt');
const Hapi = require('@hapi/hapi');
const users = {
john: {
username: 'john',
password: '$2a$10$iqJSHD.BGr0E2IxQwYgJmeP3NvhPrXAeLSaGCj6IR/XU5QtjVu5Tm',
name: 'John Doe',
id: '1'
}
};
const validate = async (request, username, password) => {
const user = users[username];
if (!user) {
return { credentials: null, isValid: false };}
const isValid = await Bcrypt.compare(password, user.password);
const credentials = { id: user.id, name: user.name };
return { isValid, credentials };
};
const start = async () => {
const server = Hapi.server({ port: 4000 });
await server.register(require('@hapi/basic'));
server.auth.strategy('simple', 'basic', { validate });
server.route({
method: 'GET',
path: '/',
options: {
auth: 'simple'},
handler(request, h) {
return 'welcome';}
});
await server.start();
console.log('Server running at: ' + server.info.uri);
};
start();
In this example, we employ the bcrypt library to hash passwords and implement basic authentication using the hapi-basic module. We define a users object that contains user data, and the validate function checks the credentials provided in the request against the stored data. The basic authentication strategy is set up using server.auth.strategy, and we define our route to require authentication.
The video "Hapi JS Tutorial 1 - Starting Your Server" provides a detailed walkthrough on getting your Hapi.js server running, including how to set up authentication.
Chapter 2: Conclusion
With Hapi.js, we can easily create a basic application complete with authentication features. This guide serves as a starting point for exploring more advanced functionalities within the Hapi framework.