Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Building Applications with Hapi.js

1. Introduction

Hapi.js is a rich framework for building applications and services in Node.js. It is designed to be flexible, allowing developers to create powerful web applications while maintaining a clear and concise structure.

2. Installation

To start using Hapi.js, you need to install it via npm. Run the following command in your terminal:

npm install @hapi/hapi

3. Creating a Server

To create a simple Hapi.js server, follow these steps:


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();
                

4. Defining Routes

Routes are fundamental in Hapi.js for handling requests. Here’s how to define a basic route:


server.route({
    method: 'GET',
    path: '/',
    handler: (request, h) => {
        return 'Hello, Hapi.js!';
    }
});
                

5. Input Validation

Hapi.js provides robust input validation using Joi. Here’s how to validate a request:


const Joi = require('joi');

server.route({
    method: 'POST',
    path: '/user',
    handler: (request, h) => {
        return `User ${request.payload.name} created!`;
    },
    options: {
        validate: {
            payload: Joi.object({
                name: Joi.string().min(3).required(),
                age: Joi.number().integer().min(0)
            })
        }
    }
});
                

6. Using Plugins

Hapi.js supports a powerful plugin system. Here’s how to register a plugin:


const HapiAuthJWT = require('@hapi/cookie');

const init = async () => {
    await server.register(HapiAuthJWT);
    // ... other setup
};
                

7. Best Practices

  • Use async/await for asynchronous code.
  • Organize routes in separate modules.
  • Utilize Hapi's built-in validation features.
  • Implement error handling globally.
  • Use environment variables for configuration.

8. FAQ

What is Hapi.js?

Hapi.js is a framework for building applications and services in Node.js, known for its rich features and flexibility.

Is Hapi.js suitable for REST APIs?

Yes, Hapi.js is well-suited for building RESTful APIs due to its routing, validation, and plugin capabilities.

How does Hapi.js compare to Express.js?

While both frameworks are used for building web applications, Hapi.js provides more structure and built-in features, while Express.js is more minimalistic and flexible.