hapi
БесплатноБез исполняемых скриптовНе проверенhapi is a Node.js web framework for building HTTP APIs from configuration: routes declare their validation, authentication, caching and CORS rules, and the…
от TerminalSkills★ 221 звезда на GitHubОб этом скилле
Hapi — Enterprise Node.js Framework
Overview
hapi (@hapi/hapi, currently 21.x) is a configuration-centric HTTP framework for Node.js. A route is an object that declares its input validation, response schema, authentication and access rules; hapi runs those steps in a fixed request lifecycle and only then calls the handler. Validation uses Joi schemas (the separate joi package), authentication is added through scheme plugins such as @hapi/jwt, and application code is organised into plugins. There is no middleware chain: cross-cutting logic goes into lifecycle extension points. Rate limiting is not built in.
Instructions
Installation
npm install @hapi/hapi joi @hapi/jwt @hapi/boom
# Optional: static files and template rendering
npm install @hapi/inert @hapi/vision
Install joi, not @hapi/joi — the scoped package is deprecated on npm ("Switch to 'npm install joi'"). TypeScript declarations ship inside @hapi/hapi, @hapi/jwt, @hapi/boom and joi; no @types/* packages are needed.
Server, authentication and routes
Register the auth scheme and strategy before adding any route that names it; otherwise server.route() throws Unknown authentication strategy jwt in /api/users.
// server.mjs
import Hapi from "@hapi/hapi";
import Jwt from "@hapi/jwt";
import Boom from "@hapi/boom";
import Joi from "joi";
import { randomUUID } from "node:crypto";
const users = new Map();
export async function createServer() {
const server = Hapi.server({
port: Number(process.env.PORT ?? 3000),
host: "0.0.0.0",
routes: {
cors: { origin: ["https://app.northwind.dev"], credentials: true },
validate: {
options: { abortEarly: false },
// Default reply is the generic "Invalid request payload input";
// rethrowing exposes Joi's message and the failing keys to the client.
failAction: (request, h, err) => { throw err; },
},
},
});
await server.register(Jwt);
server.auth.strategy("jwt", "jwt", {
keys: process.env.JWT_SECRET,
// aud, iss and sub are required unless verify is false; false skips one check
verify: { aud: "urn:audience:northwind-api", iss: "urn:issuer:northwind-auth", sub: false, maxAgeSec: 14400, timeSkewSec: 15 },
validate: (artifacts, request, h) => ({
isValid: true,
credentials: { user: artifacts.decoded.payload.user, scope: artifacts.decoded.payload.scope },
}),
});
server.auth.default("jwt"); // every route now requires a token unless it opts out
server.route({
method: "POST",
path: "/api/users",
options: {
auth: { access: { scope: ["admin"] } }, // checked against credentials.scope
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().required(),
name: Joi.string().required(),
email: Joi.string().email().required(),
role: Joi.string().valid("user", "admin").required(),
createdAt: Joi.date().required(),
}),
},
},
handler: (request, h) => {
const user = { id: randomUUID(), ...request.payload, createdAt: new Date() };
users.set(user.id, user);
return h.response(user).code(201);
},
});
server.route({
method: "GET",
path: "/api/users/{id}",
options: { validate: { params: Joi.object({ id: Joi.string().uuid().required() }) } },
handler: (request) => {
const user = users.get(request.params.id);
if (!user) throw Boom.notFound("User not found");
return user; // objects are serialised as JSON with status 200
},
});
server.route({ method: "GET", path: "/health", options: { auth: false }, handler: () => ({ status: "ok" }) });
return server;
}
if (process.argv[2] === "start") {
const server = await createServer();
await server.start();
console.log(`Listening on ${server.info.uri}`);
}
Validation rules must be compiled Joi schemas (Joi.object({...})). A plain object such as { limit: Joi.number() } fails with Cannot set uncompiled validation rules without configuring a validator unless server.validator(Joi) was called first.
Plugins, server methods and lifecycle extensions
A plugin is an object with name and an async register(server, options). Server methods are shared functions with optional caching (in-memory by default; generateTimeout is required when cache is set). server.ext() attaches to lifecycle points, which run in this order: onRequest, onPreAuth, onCredentials, onPostAuth, onPreHandler, onPostHandler, onPreResponse, onPostResponse.
// invoices.mjs
export const invoicesPlugin = {
name: "invoices",
version: "1.0.0",
register: async (server, options) => {
serve
Установить hapi в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл hapi?
hapi is a Node.js web framework for building HTTP APIs from configuration: routes declare their validation, authentication, caching and CORS rules, and the framework enforces them before the handler runs. Use when a user asks to build or fix a hapi server, validate request payloads or responses with Joi, protect routes with JWT through @hapi/jwt, split an API into hapi plugins, cache results with server methods, hook into the request lifecycle, return errors with @hapi/boom, or test routes with server.inject().
Как установить скилл hapi?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл hapi запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic