Hapi — Enterprise Node.js Framework
You are an expert in Hapi.js, the configuration-centric enterprise framework for Node.js. You help developers build production APIs with built-in input validation (Joi), authentication strategies, plugin architecture, caching, rate limiting, and comprehensive request lifecycle hooks — designed for teams that need structure, security, and testability without third-party middleware sprawl.
Core Capabilities
Server and Routes
import Hapi from "@hapi/hapi";
import Joi from "joi";
const server = Hapi.server({ port: 3000, host: "0.0.0.0",
routes: { cors: { origin: ["*"], credentials: true }, validate: { failAction: "error" } },
});
// Route with built-in validation
server.route({
method: "POST",
path: "/api/users",
options: {
tags: ["api", "users"],
description: "Create a new user",
validate: {
payload: Joi.object({
name: Joi.string().min(2).max(100).required(),
email: Joi.string().email().required(),
role: Joi.string().valid("user", "admin").default("user"),
}),
},
response: {
schema: Joi.object({
id: Joi.string().uuid(),
name: Joi.string(),
email: Joi.string(),
role: Joi.string(),
createdAt: Joi.date(),
}),
},
auth: "jwt",
},
handler: async (request, h) => {
const user = await db.users.create(request.payload);
return h.response(user).code(201);
},
});
// Auth strategy
await server.register(require("@hapi/jwt"));
server.auth.strategy("jwt", "jwt", {
keys: process.env.JWT_SECRET,
verify: { aud: "my-app", iss: "auth-service", sub: false },
validate: (artifacts) => ({
isValid: true,
credentials: { user: artifacts.decoded.payload },
}),
});
server.auth.default("jwt");
// Plugin
const usersPlugin: Hapi.Plugin<{}> = {
name: "users",
version: "1.0.0",
register: async (server) => {
server.route([
{ method: "GET", path: "/api/users", handler: listUsers },
{ method: "GET", path: "/api/users/{id}", handler: getUser },
{ method: "PUT", path: "/api/users/{id}", handler: updateUser },
{ method: "DELETE", path: "/api/users/{id}", handler: deleteUser },
]);
},
};
await server.register(usersPlugin);
await server.start();
Installation
npm install @hapi/hapi @hapi/joi @hapi/jwt @hapi/inert @hapi/vision
Best Practices
- Joi validation — Validate all input (params, query, payload, headers) at the route level; rejects bad input before handler
- Plugins for modularity — Group related routes/logic into plugins; each plugin is self-contained and testable
- Auth strategies — Register auth strategies (JWT, cookie, OAuth) via plugins; apply per-route or as default
- Response validation — Validate outgoing responses in development; catches schema drift early
- Server methods — Use
server.method() for cached, shared functions; built-in caching with TTL
- Lifecycle hooks — Use
onPreAuth, onPreHandler, onPostHandler for cross-cutting concerns (logging, metrics)
- Error handling — Use
@hapi/boom for HTTP errors; consistent error format across all routes
- Testing — Use
server.inject() for integration tests; no HTTP overhead, test routes directly
1---2name: hapi3description: >-4 You are an expert in Hapi.js, the configuration-centric enterprise5 framework for Node.js. You help developers build production APIs with6 built-in input validation (Joi), authentication strategies, plugin7 architecture, caching, rate limiting, and comprehensive request lifecycle8 hooks — designed for teams that need structure, security, and testability9 without third-party middleware sprawl.10license: Apache-2.011compatibility: ''12metadata:13 source: https://skillmd.com/skills/eliferjunior/hapi14 author: terminal-skills15 version: 1.0.016 category: Backend Development17 tags:18 - node19 - web-framework20 - enterprise21 - validation22 - auth23 - api24 - plugins25---2627# Hapi — Enterprise Node.js Framework2829You are an expert in Hapi.js, the configuration-centric enterprise framework for Node.js. You help developers build production APIs with built-in input validation (Joi), authentication strategies, plugin architecture, caching, rate limiting, and comprehensive request lifecycle hooks — designed for teams that need structure, security, and testability without third-party middleware sprawl.3031## Core Capabilities3233### Server and Routes3435```typescript36import Hapi from "@hapi/hapi";37import Joi from "joi";3839const server = Hapi.server({ port: 3000, host: "0.0.0.0",40 routes: { cors: { origin: ["*"], credentials: true }, validate: { failAction: "error" } },41});4243// Route with built-in validation44server.route({45 method: "POST",46 path: "/api/users",47 options: {48 tags: ["api", "users"],49 description: "Create a new user",50 validate: {51 payload: Joi.object({52 name: Joi.string().min(2).max(100).required(),53 email: Joi.string().email().required(),54 role: Joi.string().valid("user", "admin").default("user"),55 }),56 },57 response: {58 schema: Joi.object({59 id: Joi.string().uuid(),60 name: Joi.string(),61 email: Joi.string(),62 role: Joi.string(),63 createdAt: Joi.date(),64 }),65 },66 auth: "jwt",67 },68 handler: async (request, h) => {69 const user = await db.users.create(request.payload);70 return h.response(user).code(201);71 },72});7374// Auth strategy75await server.register(require("@hapi/jwt"));76server.auth.strategy("jwt", "jwt", {77 keys: process.env.JWT_SECRET,78 verify: { aud: "my-app", iss: "auth-service", sub: false },79 validate: (artifacts) => ({80 isValid: true,81 credentials: { user: artifacts.decoded.payload },82 }),83});84server.auth.default("jwt");8586// Plugin87const usersPlugin: Hapi.Plugin<{}> = {88 name: "users",89 version: "1.0.0",90 register: async (server) => {91 server.route([92 { method: "GET", path: "/api/users", handler: listUsers },93 { method: "GET", path: "/api/users/{id}", handler: getUser },94 { method: "PUT", path: "/api/users/{id}", handler: updateUser },95 { method: "DELETE", path: "/api/users/{id}", handler: deleteUser },96 ]);97 },98};99await server.register(usersPlugin);100101await server.start();102```103104## Installation105106```bash107npm install @hapi/hapi @hapi/joi @hapi/jwt @hapi/inert @hapi/vision108```109110## Best Practices1111121. **Joi validation** — Validate all input (params, query, payload, headers) at the route level; rejects bad input before handler1132. **Plugins for modularity** — Group related routes/logic into plugins; each plugin is self-contained and testable1143. **Auth strategies** — Register auth strategies (JWT, cookie, OAuth) via plugins; apply per-route or as default1154. **Response validation** — Validate outgoing responses in development; catches schema drift early1165. **Server methods** — Use `server.method()` for cached, shared functions; built-in caching with TTL1176. **Lifecycle hooks** — Use `onPreAuth`, `onPreHandler`, `onPostHandler` for cross-cutting concerns (logging, metrics)1187. **Error handling** — Use `@hapi/boom` for HTTP errors; consistent error format across all routes1198. **Testing** — Use `server.inject()` for integration tests; no HTTP overhead, test routes directly