by Maya Torres

hapi is a rich, production-ready Node.js framework for building scalable APIs and web applications with minimal overhead, full built-in functionality, and a strong security focus.
This block provides the full source of @hapi/hapi, a production-grade HTTP server framework for Node.js with built-in routing, authentication, validation, caching, and extension points. The typical buyer is a backend engineer building REST APIs or web services who wants fine-grained control over the request lifecycle. Drop the source into a Node.js project, wire it up, and run a hapi server without installing the upstream npm package separately.
index.js - Package entry point; exports Server constructor and server factory aliasserver.js - Top-level Server class; public API surface (route, start, stop, inject, register)core.js - Internal Core class; owns shared state (caches, events, auth, routing, listeners)request.js - Request class; represents an in-flight HTTP request with all lifecycle propertiesresponse.js - Response class; wraps response source, headers, status code, and streamingauth.js - Authentication scheme and strategy registration and enforcementcompression.js - Response compression encoder managementconfig.js - Joi-based schema definitions for all server/route configuration optionscors.js - CORS header generation and preflight handlingext.js - Lifecycle extension point (server.ext) registration and invocationhandler.js - Route handler resolution and executionheaders.js - HTTP response header utilitiesmethods.js - Server method (server.method) registration and cachingroute.js - Route object construction, validation, and matching logicsecurity.js - Security headers (Strict-Transport-Security, X-Frame-Options, etc.)streams.js - Internal readable/writable stream helpers for response payloadstoolkit.js - Response Toolkit (h) implementation available inside handlerstransmit.js - Final response transmission logic (send, pipe, finalize)validation.js - Input/output validation integration (headers, params, payload, response)Spin up an isolated sandbox and run it server-side — no local setup.
Tetrees AI Review of this version
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
Pipeline avcp-2026-08-04.1 · SHA-256 1fad73329045ebe8…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
Reviewed Aug 4, 2026
Push this product straight into your AI IDE, web builder or cloud IDE.
Connect Tetrees to a compatible AI IDE, list products you own, and request the verified ZIP without exposing seller upload controls.
No reviews yet.
Sign in to join the discussion
Loading discussion…
types/ - TypeScript declaration files for the entire public APIindex.d.ts - Re-exports top-level TypeScript typesnpm install @hapi/accept @hapi/ammo @hapi/boom @hapi/bounce @hapi/call \
@hapi/catbox @hapi/catbox-memory @hapi/heavy @hapi/hoek @hapi/mimos \
@hapi/podium @hapi/shot @hapi/somever @hapi/statehood @hapi/subtext \
@hapi/teamwork @hapi/topo @hapi/validate querystring
No native modules, pod installs, or prebuild steps are required. Node.js >= 18 is expected by hapi 21.x.
source/ directory into your project, e.g. src/hapi-lib/.// CommonJS
const Hapi = require('./src/hapi-lib/index.js');
or with a TypeScript path alias:
// tsconfig.json
{
"compilerOptions": {
"paths": {
"@hapi/hapi": ["./src/hapi-lib/index.d.ts"]
}
}
}
server.start() configuration.typeRoots or types at source/types/ for the bundled declarations.import { Server } from './src/hapi-lib/index.js';
const server: Server = new Server(options?: ServerOptions);
// -or-
const server = require('./src/hapi-lib/index.js').server(options);
Server is both a class and a callable factory (the default export of server.js is a function that returns a new internals.Server instance wrapping a Core). Use it to create a server instance, register plugins, define routes, and control the lifecycle via server.start() / server.stop().
class Request {
server: Server;
method: string;
path: string;
query: Record<string, string>;
params: Record<string, string>;
payload: unknown;
headers: Record<string, string>;
state: Record<string, string>;
auth: { isAuthenticated: boolean; credentials: unknown };
app: Record<string, unknown>;
plugins: Record<string, unknown>;
pre: Record<string, unknown>;
logs: object[];
info: object;
response: Response | null;
raw: { req: IncomingMessage; res: ServerResponse };
}
Request is instantiated internally per incoming HTTP request. Inside handlers, lifecycle extensions, and pre-handler methods, the first argument is a Request instance. Read request.payload for body data, request.auth.credentials for authenticated identity, and request.app for per-request custom state.
class Response {
statusCode: number;
headers: Record<string, string>;
source: unknown;
variety: string;
app: Record<string, unknown>;
plugins: Record<string, unknown>;
settings: {
charset: string;
encoding: string;
ttl: number | null;
passThrough: boolean;
};
code(statusCode: number): this;
header(name: string, value: string, options?: object): this;
type(mimeType: string): this;
ttl(msec: number): this;
state(name: string, value: unknown, options?: object): this;
}
Response is the object returned by the response toolkit h.response(source). Chain methods to set status code, headers, content type, cookies, and caching TTL before the response is transmitted.
A minimal server that handles GET and POST routes, returning JSON.
const Hapi = require('./src/hapi-lib/index.js');
async function start() {
const server = Hapi.server({ port: 3000, host: 'localhost' });
server.route({
method: 'GET',
path: '/users/{id}',
handler(request, h) {
return { id: request.params.id, name: 'Alice' };
}
});
server.route({
method: 'POST',
path: '/users',
handler(request, h) {
const body = request.payload as { name: string };
return h.response({ created: body.name }).code(201);
}
});
await server.start();
console.log(`Server running on ${server.info.uri}`);
}
start().catch(console.error);
Using hapi's plugin system and server.method for cached computations.
const Hapi = require('./src/hapi-lib/index.js');
const myPlugin = {
name: 'myPlugin',
version: '1.0.0',
register(server: any, options: any) {
server.method('greet', (name: string) => `Hello, ${name}!`, {
cache: { expiresIn: 60000, generateTimeout: 2000 }
});
server.route({
method: 'GET',
path: '/greet/{name}',
async handler(request, h) {
const message = await request.server.methods.greet(request.params.name);
return { message };
}
});
}
};
async function start() {
const server = Hapi.server({ port: 3000 });
await server.register(myPlugin);
await server.start();
}
start().catch(console.error);
Registering an onPreResponse extension and a custom auth scheme.
const Hapi = require('./src/hapi-lib/index.js');
const Boom = require('@hapi/boom');
async function start() {
const server = Hapi.server({ port: 3000 });
// Custom auth scheme
server.auth.scheme('token', (srv, options) => ({
authenticate(request, h) {
const token = request.headers['x-token'];
if (token !== 'secret') throw Boom.unauthorized('Invalid token');
return h.authenticated({ credentials: { user: 'alice' } });
}
}));
server.auth.strategy('simple', 'token');
// Global lifecycle extension to normalize errors
server.ext('onPreResponse', (request, h) => {
if (request.response instanceof Error) {
const err = request.response as any;
return h.response({ error: err.message }).code(err.output?.statusCode ?? 500);
}
return h.continue;
});
server.route({
method: 'GET',
path: '/secret',
options: { auth: 'simple' },
handler(request, h) {
return { user: (request.auth.credentials as any).user };
}
});
await server.start();
}
start().catch(console.error);
index.js - Exports Server (class) and server (alias); the sole public entry point.server.js - Defines internals.Server; implements route, start, stop, register, inject, ext, auth, decorate, cache.core.js - Core class holds shared infrastructure: event bus (Podium), router (@hapi/call), cache clients (Catbox), and server state.request.js - Request class; initialized per connection with lifecycle flags, route reference, and all request-scoped properties.response.js - Response class; manages source (buffer, stream, object), headers, status code, and chainable mutators.auth.js - Manages auth scheme/strategy registry; invokes authenticate/payload/response auth steps.compression.js - Wraps encoder negotiation; integrates with @hapi/accept and zlib.config.js - Centralized Joi schemas for validating server options, route options, and plugin options.cors.js - Generates Access-Control-* headers and handles OPTIONS preflight routes.ext.js - Stores and sequences lifecycle extension functions per point (e.g. onPreAuth, onPostHandler).handler.js - Resolves the route handler function and wraps execution with error handling.headers.js - Sets Content-Type, Content-Length, ETag, Last-Modified, and cache-control headers.methods.js - Implements server.method with optional Catbox caching and argument-based cache keys.route.js - Builds Route objects from configuration; compiles path patterns and merges settings.security.js - Applies security-related response headers from route options.security config.streams.js - Peek and Recorder transform streams used internally during payload and response processing.toolkit.js - Response Toolkit (h); provides h.response(), h.redirect(), h.authenticated(), h.continue, h.entity().transmit.js - Handles final response write: determines variety, pipes streams, applies compression, ends response.validation.js - Runs Joi/custom validators against request path params, query, headers, payload, and response.types/ - TypeScript declarations mirroring each runtime module; consumed by TS projects for type safety.'use strict' + require; do not use import directly — use require or a CJS-to-ESM wrapper.actives = new WeakMap()). Fix: upgrade Node or transpile with Babel.@hapi/validate peer: Several internal schemas use @hapi/validate, not joi directly; ensure @hapi/validate is installed and not aliased to Joi 17 without compatibility shim.querystring module: Node 18+ deprecates the built-in querystring; request.js still imports it. It remains available but pin Node < 22 or replace with new URLSearchParams.h.authenticated(): Returning a plain object from authenticate() will not set request.auth.credentials; always use return h.authenticated({ credentials }).name field required: Registering an object plugin without a name property throws synchronously inside core.js registration — always include name and version.I have a local copy of the @hapi/hapi 21.4.8 framework source in `src/hapi-lib/`
and a USAGE.md guide at the root of my project.
Please read USAGE.md and the files in src/hapi-lib/ (especially index.js,
server.js, request.js, response.js, and toolkit.js), then integrate hapi
into my project by doing the following step by step:
1. Replace any existing HTTP server setup with a hapi Server instance created
from `src/hapi-lib/index.js` (not from the npm package).
2. Convert my existing Express/native routes to hapi route objects using
server.route({ method, path, handler }).
3. Register any middleware equivalents as hapi lifecycle extensions via
server.ext('onPreResponse', ...) or server.ext('onPreAuth', ...).
4. If I have authentication, implement a hapi auth scheme via
server.auth.scheme() and server.auth.strategy() using the patterns in
USAGE.md.
5. Ensure all dependencies in USAGE.md ## Required dependencies are installed.
6. Show the final server startup code with server.start() and error handling.
Only use exports and APIs documented in USAGE.md and visible in src/hapi-lib/.
Do not import from @hapi/hapi npm package directly.
@hapi/hapi is released under the BSD 3-Clause License. See source/LICENSE if present, or refer to the upstream repository. Upstream package: @hapi/hapi@21.4.8 — documentation and API reference at hapi.dev.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
The full install guide and integration prompts unlock after purchase.
Automation, Utilities & Developer Tools
Free