or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mdcore-framework.mderror-handling.mdevent-handling.mdhandlers-middleware.mdindex.mdrequest-processing.mdresponse-handling.mdruntime-adapters.mdweb-utilities.md
tile.json

tessl/npm-h3

Minimal H(TTP) framework built for high performance and portability across multiple JavaScript runtimes.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/h3@2.0.x

To install, run

npx @tessl/cli install tessl/npm-h3@2.0.0

index.mddocs/

H3

H3 is a minimal HTTP framework built for high performance and portability across multiple JavaScript runtimes. It provides a comprehensive set of utilities for building HTTP servers with event handling, middleware support, routing capabilities, request/response processing, and multi-runtime compatibility including Node.js, Deno, Bun, Cloudflare Workers, Service Workers, and generic environments.

Package Information

  • Package Name: h3
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install h3

Core Imports

import { H3, defineHandler, H3Event } from "h3";

For CommonJS:

const { H3, defineHandler, H3Event } = require("h3");

Runtime-specific imports:

// Node.js specific
import { H3 } from "h3/node";

// Deno specific
import { H3 } from "h3/deno";

// Bun specific
import { H3 } from "h3/bun";

// Cloudflare Workers
import { H3 } from "h3/cloudflare";

// Service Worker
import { H3 } from "h3/service-worker";

// Generic (platform-agnostic)
import { H3 } from "h3/generic";

Basic Usage

import { H3, defineHandler, getQuery, readBody } from "h3";

// Create H3 application
const app = new H3();

// Define a simple handler
const handler = defineHandler(async (event) => {
  return { message: "Hello from H3!" };
});

// Add routes
app.get("/", handler);
app.post("/api/users", defineHandler(async (event) => {
  const body = await readBody(event);
  return { created: body };
}));

// Add middleware
app.use("/api", defineHandler(async (event) => {
  console.log(`${event.method} ${event.url}`);
}));

// For Node.js
import { toNodeHandler } from "h3";
import { createServer } from "http";

const server = createServer(toNodeHandler(app));
server.listen(3000);

Architecture

H3 is built around several key components:

  • H3 Application: Main application class that handles routing, middleware, and request processing
  • Event System: H3Event represents the request/response context with unified API across runtimes
  • Handler System: Type-safe event handlers with middleware support and lazy loading
  • Middleware Pipeline: Flexible middleware system with route matching and error handling
  • Runtime Adapters: Adapters for different JavaScript runtimes and deployment targets
  • Utility Functions: Comprehensive utilities for common HTTP operations

Capabilities

Core Framework

Main application class and plugin system for creating HTTP servers with routing, middleware, and multi-runtime support.

class H3 {
  constructor(config?: H3Config);
  fetch(request: ServerRequest): Response | Promise<Response>;
  register(plugin: H3Plugin): this;
  mount(base: string, input: FetchHandler | { fetch: FetchHandler } | H3): this;
  use(handler: Middleware, opts?: MiddlewareOptions): this;
  use(route: string, handler: Middleware, opts?: MiddlewareOptions): this;
  on(method: HTTPMethod, route: string, handler: EventHandler, opts?: RouteOptions): this;
  get(route: string, handler: EventHandler, opts?: RouteOptions): this;
  post(route: string, handler: EventHandler, opts?: RouteOptions): this;
  put(route: string, handler: EventHandler, opts?: RouteOptions): this;
  delete(route: string, handler: EventHandler, opts?: RouteOptions): this;
  patch(route: string, handler: EventHandler, opts?: RouteOptions): this;
  head(route: string, handler: EventHandler, opts?: RouteOptions): this;
  options(route: string, handler: EventHandler, opts?: RouteOptions): this;
}

function definePlugin<T>(def: (h3: H3, options: T) => void): H3Plugin;

Core Framework

Event Handling

Event system providing unified request/response context across all JavaScript runtimes with type-safe event manipulation.

class H3Event {
  req: TypedServerRequest;
  url: URL;
  context: H3EventContext;
  app?: H3Core;
  res: H3EventResponse;
  runtime?: ServerRuntimeContext;
  
  waitUntil(promise: Promise<any>): void;
  toString(): string;
  toJSON(): string;
}

function isEvent(input: any): input is H3Event;
function isHTTPEvent(input: any): input is HTTPEvent;
function mockEvent(request: string | URL | Request, options?: RequestInit & { h3?: H3EventContext }): H3Event;
function getEventContext<T>(event: HTTPEvent | H3Event): T;

Event Handling

Handler and Middleware System

Type-safe handler definition system with middleware support, validation, lazy loading, and dynamic routing.

function defineHandler<Req, Res>(handler: EventHandler<Req, Res>): EventHandlerWithFetch<Req, Res>;
function defineHandler<Req, Res>(def: EventHandlerObject<Req, Res>): EventHandlerWithFetch<Req, Res>;
function defineValidatedHandler<T>(def: EventHandlerObject<T>): EventHandlerWithFetch<T>;
function defineLazyEventHandler(load: () => Promise<EventHandler> | EventHandler): EventHandlerWithFetch;
function dynamicEventHandler(initial?: EventHandler): DynamicEventHandler;

function defineMiddleware(input: Middleware): Middleware;
function onRequest(hook: (event: H3Event) => void | Promise<void>): Middleware;
function onResponse(hook: (response: Response, event: H3Event) => MaybePromise<void | Response>): Middleware;
function onError(hook: (error: HTTPError, event: H3Event) => MaybePromise<void | unknown>): Middleware;

Handler and Middleware System

Request Processing

Comprehensive request handling utilities for parsing query parameters, route parameters, request body, headers, and HTTP method validation.

function getQuery<T>(event: HTTPEvent): T;
function getValidatedQuery<T>(event: HTTPEvent, validate: Function): Promise<T>;
function getRouterParams(event: HTTPEvent, opts?: { decode?: boolean }): Record<string, string>;
function getRouterParam(event: HTTPEvent, name: string, opts?: { decode?: boolean }): string | undefined;
function getValidatedRouterParams<T>(event: HTTPEvent, validate: Function, opts?: { decode?: boolean }): Promise<T>;
function readBody<T>(event: HTTPEvent): Promise<T | undefined>;
function readValidatedBody<T>(event: HTTPEvent, validate: Function): Promise<T>;
function isMethod(event: HTTPEvent, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): boolean;
function assertMethod(event: HTTPEvent, expected: HTTPMethod | HTTPMethod[], allowHead?: boolean): void;
function getRequestURL(event: HTTPEvent, opts?: RequestURLOptions): URL;
function getRequestHost(event: HTTPEvent, opts?: { xForwardedHost?: boolean }): string | undefined;
function getRequestProtocol(event: HTTPEvent, opts?: { xForwardedProto?: boolean }): string;
function getRequestIP(event: HTTPEvent, opts?: { xForwardedFor?: boolean }): string | undefined;

Request Processing

Response Handling

Response utilities for sending different content types, redirects, status codes, and streaming responses.

function redirect(event: H3Event, location: string, code?: number): string;
function noContent(event: H3Event, code?: number): Response;
function html(event: H3Event, content: string): string;
function writeEarlyHints(event: H3Event, hints: Record<string, string>): void | Promise<void>;
function iterable<Value, Return>(event: H3Event, iterable: IterationSource<Value, Return>, options?: IterableOptions): ReadableStream;
function toResponse(val: unknown, event: H3Event, config?: H3Config): Response | Promise<Response>;

Response Handling

Error Handling

HTTP error handling with status codes, custom error data, and structured error responses.

class HTTPError extends Error {
  status: number;
  statusText: string | undefined;
  headers: Headers | undefined;
  cause: unknown | undefined;
  data: T | undefined;
  body: Record<string, unknown> | undefined;
  unhandled: boolean | undefined;
  
  constructor(message: string, details?: ErrorDetails);
  constructor(details: ErrorDetails);
  toJSON(): ErrorBody;
  
  static isError(input: any): input is HTTPError;
  static status(status: number, statusText?: string, details?: ErrorDetails): HTTPError;
}

Error Handling

Web Utilities

Essential web utilities including cookie management, session handling, CORS support, authentication, caching, and static file serving.

// Cookies
function parseCookies(event: HTTPEvent): Record<string, string>;
function getCookie(event: HTTPEvent, name: string): string | undefined;
function getChunkedCookie(event: HTTPEvent, name: string): string | undefined;
function setCookie(event: H3Event, name: string, value: string, options?: CookieSerializeOptions): void;
function setChunkedCookie(event: H3Event, name: string, value: string, options?: CookieSerializeOptions): void;
function deleteCookie(event: H3Event, name: string, serializeOptions?: CookieSerializeOptions): void;
function deleteChunkedCookie(event: H3Event, name: string, options?: CookieSerializeOptions): void;

// Sessions
function useSession<T>(event: HTTPEvent, config: SessionConfig): Promise<SessionManager<T>>;
function getSession<T>(event: HTTPEvent, config: SessionConfig): Promise<Session<T>>;
function updateSession<T>(event: HTTPEvent, config: SessionConfig, update?: SessionUpdate<T>): Promise<Session<T>>;

// CORS
function handleCors(event: H3Event, options: CorsOptions): false | Response;
function appendCorsHeaders(event: H3Event, options: CorsOptions): void;
function appendCorsPreflightHeaders(event: H3Event, options: CorsOptions): void;
function isPreflightRequest(event: HTTPEvent): boolean;
function isCorsOriginAllowed(origin: string, options: CorsOptions): boolean;

// Authentication
function basicAuth(opts: BasicAuthOptions): Middleware;
function requireBasicAuth(event: HTTPEvent, opts: BasicAuthOptions): Promise<true>;

Web Utilities

Advanced Features

Advanced features including proxy functionality, Server-Sent Events (SSE), WebSocket support, static file serving, and caching.

// Proxy
function proxy(event: H3Event, target: string, opts?: ProxyOptions): Promise<BodyInit | undefined | null>;
function proxyRequest(event: H3Event, target: string, opts?: ProxyOptions): Promise<Response>;
function getProxyRequestHeaders(event: H3Event, opts?: { xForwardedFor?: boolean }): Record<string, string>;
function fetchWithEvent(event: H3Event, req: ServerRequest | URL | string, init?: RequestInit): Promise<Response>;

// Server-Sent Events
function createEventStream(event: H3Event, options?: EventStreamOptions): EventStreamHelper;

// WebSockets
function defineWebSocketHandler(hooks: Partial<WSHooks>): EventHandler;
function defineWebSocket(hooks: Partial<WSHooks>): Partial<WSHooks>;

// Static Files
function serveStatic(event: H3Event, options: ServeStaticOptions): Promise<Response | undefined>;

// Caching
function handleCacheHeaders(event: H3Event, opts: CacheConditions): boolean;

Advanced Features

Runtime Adapters

Adapters for integrating H3 with different JavaScript runtimes and deployment platforms including Node.js, Web standards, and legacy systems.

function toNodeHandler(app: H3): NodeHandler;
function fromNodeHandler(handler: NodeHandler | NodeMiddleware): EventHandler;
function defineNodeHandler(handler: NodeHandler): NodeHandler;
function defineNodeMiddleware(handler: NodeMiddleware): NodeMiddleware;
function fromWebHandler(handler: (...) => Promise<Response>): EventHandler;
function toWebHandler(app: H3): (request: ServerRequest, context?: H3EventContext) => Promise<Response>;

Runtime Adapters

Types

Core Types

type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' | 'CONNECT' | 'TRACE';

interface H3Config {
  debug?: boolean;
  silent?: boolean;
  plugins?: H3Plugin[];
  onError?: (error: HTTPError, event: H3Event) => MaybePromise<void | unknown>;
  onRequest?: (event: H3Event) => MaybePromise<void>;
  onResponse?: (response: Response, event: H3Event) => MaybePromise<void | Response>;
}

interface H3EventContext {
  [key: string]: any;
}

type H3Plugin = (h3: H3, options?: any) => void;

interface RouteOptions {
  meta?: H3RouteMeta;
}

interface MiddlewareOptions {
  meta?: H3RouteMeta;
}

Handler Types

type EventHandler<RequestT = any, ResponseT = any> = (event: H3Event) => ResponseT | Promise<ResponseT>;

interface EventHandlerObject<RequestT = any, ResponseT = any> {
  handler: EventHandler<RequestT, ResponseT>;
  onRequest?: Middleware[];
  onResponse?: Middleware[];
  onError?: Middleware[];
}

type Middleware = (event: H3Event) => void | Promise<void>;

interface DynamicEventHandler {
  set(handler: EventHandler): void;
  handler: EventHandler;
}

Error Types

interface ErrorDetails {
  status?: number;
  statusText?: string;
  headers?: HeadersInit;
  cause?: unknown;
  data?: any;
}

interface ErrorBody<DataT = any> {
  message: string;
  status?: number;
  statusText?: string;
  data?: DataT;
}

Utility Types

interface RequestURLOptions {
  xForwardedHost?: boolean;
  xForwardedProto?: boolean;
}

interface SessionManager<T> {
  data: T;
  update(data: Partial<T>): Promise<void>;
  clear(): Promise<void>;
}

type SessionUpdate<T> = Partial<T> | ((oldData: T) => Partial<T> | undefined);

interface EventStreamHelper {
  push(message: string | EventStreamMessage): Promise<void>;
  close(): Promise<void>;
}

interface EventStreamMessage {
  id?: string;
  event?: string;
  data?: string;
  retry?: number;
}

type MaybePromise<T> = T | Promise<T>;