# blade47/hono Wiki ## Technical docs: Overview URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/overview
Relevant source files The following files were used as context for generating this wiki page: - [src/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts) - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts) - [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts) - [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts) - [jsr.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts) - [src/adapter/netlify/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/index.ts) - [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts) - [src/adapter/deno/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts) - [src/helper/ssg/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/index.ts) - [src/adapter/aws-lambda/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/index.ts) - [src/helper/accepts/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/index.ts)
## Overview Hono is a lightweight web framework built natively on [Runtime Adapters](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/runtime-adapters) and Web Standard request-response interfaces [src/index.ts:4-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L4-L4). By exposing modular components through package export maps in [Project Structure](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/project-structure), it provides unified [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) primitives across diverse edge, serverless, and container environments src/index.ts:1-53, package.json:601-622. Applications leverage configurable routing engines like [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router), [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers), [Linear and Pattern Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers), alongside zero-dependency [JSX Components and Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-components-and-context) and [Static Site Generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation) utilities src/hono-base.ts:65, src/preset/quick.ts:20-22, src/preset/tiny.ts:18, src/middleware/jsx-renderer/index.ts:9, src/adapter/deno/index.ts:7. Sources: [src/index.ts:4-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L4-L4), [src/hono-base.ts:65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L65-L65), [package.json:601-622](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L601-L622), [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22), [src/preset/tiny.ts:18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L18-L18), [src/adapter/deno/index.ts:7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts#L7-L7), [src/middleware/jsx-renderer/index.ts:9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L9-L9), [src/index.ts:1-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L1-L53). ## Architectural Foundation on Web Standards ### Core Web Primitives Hono is built natively on top of Web Standard primitives such as `Request`, `Response`, and `URL`, allowing handlers to interface directly with standard fetch-handler signatures without proprietary wrapper layers [src/index.ts:4-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L4-L4). The core `Hono` class processes incoming standard requests through a unified [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) and dispatches them via modular middleware pipelines src/index.ts:8-14, package.json:601-622. ```typescript /** * @module * * Hono - Web Framework built on Web Standards * * @example * ```ts * import { Hono } from 'hono' * const app = new Hono() * * app.get('/', (c) => c.text('Hono!')) * * export default app * ``` */ ``` Sources: [src/index.ts:1-15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L1-L15) ### Design Philosophy and Runtimes The framework's design philosophy prioritizes zero-dependency portability, enabling the exact same application code to run seamlessly across diverse JavaScript execution environments [src/index.ts:4-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L4-L4). By leveraging Web APIs directly, Hono eliminates runtime-specific abstraction overhead and integrates cleanly with edge computing platforms, serverless functions, and local development servers [package.json:650-666](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L650-L666). | Runtime Target | Adapter Entry Point | Standard Request Mapping | | :--- | :--- | :--- | | Cloudflare Workers | `cloudflare-workers` | Native `FetchEvent` or module worker `fetch` handler | | Deno | `deno` | `Deno.serve` standard HTTP listener | | Bun | `bun` | Native `Bun.serve` fetch dispatcher | | AWS Lambda | `aws-lambda` | API Gateway / Lambda Function URL event conversion | Sources: [package.json:596-622](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L596-L622), [package.json:650-666](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L650-L666) ## Public Entry Points and Packaging ### Package Configuration and Distribution Hono is distributed as an ESM-first module package supporting both npm and JSR registries, configured via standard package manifests and export maps package.json:2-8, jsr.json:1-3. The package maps its primary entry point to `src/index.ts`, exposing essential application primitives, context managers, and type definitions src/index.ts:1-53, package.json:5-8. ```typescript import { Hono } from './hono' /** * Types for environment variables, error handlers, handlers, middleware handlers, and more. */ export type { Env, ErrorHandler, Handler, MiddlewareHandler, Next, NotFoundResponse, NotFoundHandler, ValidationTargets, Input, Schema, ToSchema, TypedResponse, } from './types' ``` Sources: [src/index.ts:17-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L17-L35) ### Export Maps and Subpath Modules Granular subpath exports in [Project Structure](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/project-structure) enable consumers to import specific middleware, helpers, routers, and runtime adapters directly without pulling in unused framework code package.json:596-637, jsr.json:8-106. | Subpath Identifier | Target Source Path | Primary Purpose | | :--- | :--- | :--- | | `.` | `./src/index.ts` | Core framework and type definitions | | `./tiny` | `./src/preset/tiny.ts` | Minimalist build configuration [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds) | | `./quick` | `./src/preset/quick.ts` | Optimized preset bundle [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds) | | `./bun` | `./src/adapter/bun/index.ts` | [Bun Adapter](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/bun-adapter) runtime integration | | `./deno` | `./src/adapter/deno/index.ts` | [Deno Adapter](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/deno-adapter) runtime integration | | `./validator` | `./src/validator/index.ts` | Request [Validation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/validation) helper | Sources: [package.json:602-606](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L602-L606), [jsr.json:13-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L13-L14), [jsr.json:57](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L57-L57) ## Configurable Router Architecture Selection ### Router Implementations and Modules Hono provides multiple router implementations designed for varying performance profiles, bundle size constraints, and matching algorithms src/router/smart-router/index.ts:1-6, src/router/linear-router/index.ts:1-6, src/router/pattern-router/index.ts:1-6, src/router/trie-router/index.ts:1-6. Each router is exposed via dedicated subpath modules allowing applications to select the precise matching backend src/router/smart-router/index.ts:6-6, src/router/linear-router/index.ts:6-6, src/router/pattern-router/index.ts:6-6, src/router/trie-router/index.ts:6-6. | Router Module | Exported Class | Description | | :--- | :--- | :--- | | `src/router/smart-router/index.ts` | `SmartRouter` | Heuristically chooses between router backends at initialization time [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers) | | `src/router/trie-router/index.ts` | `TrieRouter` | Traverses path segments using node trees for hierarchical matching [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers) | | `src/router/pattern-router/index.ts` | `PatternRouter` | Executes basic regular expression evaluation for lightweight builds [Linear and Pattern Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers) | | `src/router/linear-router/index.ts` | `LinearRouter` | Performs simple route array scans for minimal bundle overhead [Linear and Pattern Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers) | Sources: [src/router/smart-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts#L1-L6), [src/router/linear-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts#L1-L6), [src/router/pattern-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts#L1-L6), [src/router/trie-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts#L1-L6) ### Heuristic Selection Strategies The [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router) and SmartRouter engine variants evaluate registered route patterns to determine optimal dispatch strategies [src/router/smart-router/index.ts:3-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts#L3-L6). By analyzing route complexity and parameter structures, Hono selects matching engines that balance memory footprint against lookup speed [src/router/smart-router/index.ts:3-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts#L3-L6). > [!NOTE] > `SmartRouter` inspects registered routes during initialization to dynamically delegate matching operations to the most efficient underlying router backend [src/router/smart-router/index.ts:3-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts#L3-L6). Sources: [src/router/smart-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts#L1-L6) ## Multi-Runtime Execution Engine Compatibility ### Adapter Handler Implementations Hono decouples application core routing from underlying serverless and edge hosting platforms by providing adapter handler wrappers src/adapter/cloudflare-pages/handler.ts:32-46, src/adapter/netlify/handler.ts:4-9, src/adapter/vercel/handler.ts:4-8. These handlers translate platform-specific request contexts and event structures into standard Web API `Request` and `Response` objects consumed by `app.fetch()` src/adapter/cloudflare-pages/handler.ts:37-45, src/adapter/netlify/handler.ts:8-8, src/adapter/vercel/handler.ts:7-7. | Hosting Platform | Adapter Module | Handler Signature | | :--- | :--- | :--- | | Cloudflare Pages | `src/adapter/cloudflare-pages/handler.ts` | `handle(app: Hono): PagesFunction` | | Netlify | `src/adapter/netlify/handler.ts` | `handle(app: Hono): (req: Request, context: any) => Response \| Promise` | | Vercel | `src/adapter/vercel/handler.ts` | `handle(app: Hono): (req: Request) => Response \| Promise` | Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46), [src/adapter/netlify/handler.ts:4-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L9), [src/adapter/vercel/handler.ts:4-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts#L4-L8) ```typescript export const handle = (app: Hono) => (req: Request): Response | Promise => { return app.fetch(req) } ``` Sources: [src/adapter/vercel/handler.ts:4-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts#L4-L8) ### Cloudflare Pages and Workerd Integrations The Cloudflare Pages adapter exposes specialized execution utilities including `handleMiddleware` and `serveStatic` alongside the primary `handle` entry point [src/adapter/cloudflare-pages/handler.ts:32-122](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L122). It wraps incoming `EventContext` objects, extending environment bindings with `waitUntil`, `passThroughOnException`, and asset fetching capabilities src/adapter/cloudflare-pages/handler.ts:12-45, src/adapter/cloudflare-pages/handler.ts:114-122. > [!NOTE] > `serveStatic()` queries the `ASSETS` fetcher binding provided by Cloudflare Pages advanced mode and automatically maps 404 responses to Hono's `c.notFound()` [src/adapter/cloudflare-pages/handler.ts:108-122](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L108-L122). ```typescript export const handle = ( app: Hono ): PagesFunction => (eventContext) => { return app.fetch( eventContext.request, { ...eventContext.env, eventContext }, { waitUntil: eventContext.waitUntil, passThroughOnException: eventContext.passThroughOnException, props: {}, } ) } ``` Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46) Runtime tests for `workerd` validate environment variable extraction, runtime key resolution via `getRuntimeKey()`, WebSocket upgrades, and color support across worker boundaries [runtime-tests/workerd/index.ts:1-29](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts#L1-L29). ```typescript const app = new Hono() app.get('/', (c) => c.text(`Hello from ${getRuntimeKey()}`)) app.get('/env', (c) => { const { NAME } = env<{ NAME: string }>(c) return c.text(NAME) }) ``` Sources: [runtime-tests/workerd/index.ts:6-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts#L6-L14) ## Framework Integration Ecosystem ### Build Pipeline and Package Exports Hono structures its distribution using precise package export definitions that map deep imports to specific compiled type declarations and JavaScript bundles package.json:5-8, package.json:596-622. Platform adapters and internal helpers expose modular sub-paths so bundlers can tree-shake unused runtimes and build targets [package.json:596-622](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L596-L622). | Sub-path Export | Type Declaration Path | Target Platform / Purpose | | :--- | :--- | :--- | | `cloudflare-workers` | `./dist/types/adapter/cloudflare-workers` | Cloudflare Workers runtime adapter | | `cloudflare-pages` | `./dist/types/adapter/cloudflare-pages` | Cloudflare Pages runtime adapter | | `deno` | `./dist/types/adapter/deno` | Deno runtime adapter | | `bun` | `./dist/types/adapter/bun` | Bun runtime adapter | | `aws-lambda` | `./dist/types/adapter/aws-lambda` | AWS Lambda serverless adapter | | `vercel` | `./dist/types/adapter/vercel` | Vercel serverless functions adapter | | `netlify` | `./dist/types/adapter/netlify` | Netlify functions adapter | Sources: [package.json:5-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L5-L8), [package.json:596-615](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L596-L615) > [!NOTE] > The root package configuration specifies `"type": "module"` and enforces Node `16.9.0` or higher, ensuring native ES module resolution across tooling pipelines package.json:6-6, package.json:697-699. Sources: [package.json:6-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L6-L6), [package.json:697-699](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L697-L699) ## Where to go next | I want to… | Read | | --- | --- | | How to build, run, and export a minimal, runnable Web Standard Hono application across various runtimes with copy-pasteable examples. | [Quick Start](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/quick-start) | | What each top-level and source directory in the repository does, and how components like adapters, routers, JSX, and middleware are organized. | [Project Structure](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/project-structure) | | How the central Hono and HonoBase classes instantiate, manage routing tables, handle sub-app mounting, and expose HTTP method registrations. | [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) | | How incoming Web Standard Request objects are received, dispatched through dispatchers, parsed, and converted to Response instances. | [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle) | | How the Context class wraps requests, exposes typed parameter/header accessors, manages response rendering, and interacts with environment bindings. | [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) | | How the compose function implements the onion-model middleware chain and handles asynchronous next flow and handler pipeline execution. | [Middleware Composition](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/middleware-composition) | | How lightweight and custom distribution bundles like hono/quick and hono/tiny minimize bundle overhead for size-constrained environments. | [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds) | | How the unified Router abstract interface is structured, defining method registrations, route matching, and match result representations across all router implementations. | [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) | | How Hono's flagship RegExpRouter compiles route trees and wildcards into single regular expressions for ultrafast matching without looping. | [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router) | | How TrieRouter traverses path segments using node trees and how SmartRouter heuristically chooses between router backends at initialization time. | [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers) | | How the lightweight LinearRouter and PatternRouter execute simple route array scans or basic regex evaluation for tiny bundles. | [Linear and Pattern Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers) | | How Hono adapts to Cloudflare Workers and Cloudflare Pages environments, exposing execution contexts, bindings, and module asset serving. | [Runtime Adapters](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/runtime-adapters) | | How Hono integrates with Bun's native HTTP server, static file reader, connection info APIs, and native WebSocket implementation. | [Bun Adapter](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/bun-adapter) | | How Hono runs on Deno via Deno.serve, mapping connection metadata, static file assets, SSG builds, and Deno WebSockets. | [Deno Adapter](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/deno-adapter) | | How Hono validates, signs, decodes, and caches JSON Web Tokens and JSON Web Key Sets using standard Web Crypto APIs. | [JWT and JWK](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/jwt-and-jwk) | | How Hono handles standard HTTP Basic authentication credentials and Bearer token parsing using constant-time buffer comparisons. | [Basic and Bearer Auth](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/basic-and-bearer-auth) | | How the secure-headers and CORS middlewares configure Content-Security-Policy, HSTS, cross-origin rules, and Permissions-Policy headers. | [Secure Headers and CORS](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/secure-headers-and-cors) | | How Cross-Site Request Forgery origin checks protect mutating requests and how body-limit middleware prevents payload overflow vulnerabilities. | [CSRF and Body Limit](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/csrf-and-body-limit) | | How the IP restriction middleware parses, matches, and blocks or allows client IPv4/IPv6 addresses and CIDR subnets. | [IP Restriction](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/ip-restriction) | | How ETag generation via SHA-1/digest algorithms and Cache-Control middleware leverage Web Standard Cache APIs to manage conditional responses. | [ETag and Cache](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/etag-and-cache) | | How the compress middleware uses Accept-Encoding negotiation and Web Streams CompressionStream to encode responses with gzip or deflate. | [Response Compression](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/response-compression) | | How the logger prints colorized HTTP request traces and how Server-Timing middleware records operational durations for debugging. | [Logger and Timing](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/logger-and-timing) | | How request-id generates and injects unique trace identifiers and how language middleware negotiates locales via Accept-Language headers. | [Request ID and Language](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/request-id-and-language) | | How trailing-slash normalization routes URLs cleanly and how method-override supports PUT/DELETE verbs from standard HTML forms. | [Trailing Slash and Override](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/trailing-slash-and-override) | | How AsyncLocalStorage-backed context-storage enables global access to the current request Context without explicit parameter passing. | [Context Storage](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/context-storage) | | How Hono's zero-dependency JSX implementation compiles JSX element trees, handles raw HTML strings, and serializes DOM output asynchronously. | [JSX Runtime](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-runtime) | | How intrinsic HTML elements, Fragment, createContext, and jsx-renderer middleware provide component trees and shared state in server-rendered templates. | [JSX Components and Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-components-and-context) | | How the Suspense component and renderToReadableStream facilitate out-of-order chunked HTML streaming across modern edge runtimes. | [JSX Streaming and Suspense](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-streaming-and-suspense) | | How hono/jsx/dom renders interactive client-side JSX to browser DOM nodes using reactive hooks like useState, useEffect, and useMemo. | [Client DOM and Hooks](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/client-dom-and-hooks) | | How hono/css generates scoped class names, manages style injection, and enables critical CSS extraction for server-rendered and client JSX. | [CSS Styling](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/css-styling) | | How hc provides end-to-end type-safe client RPC calls using TypeScript type inference directly from the Hono application definition. | [RPC Client](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/rpc-client) | | How the validator helper parses and validates JSON, query strings, URL parameters, and forms with third-party schema libraries or custom rules. | [Validation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/validation) | | How stream, streamText, and streamSSE helpers handle chunked binary/text streams and Server-Sent Events with automatic backpressure. | [Streaming and SSE](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/streaming-and-sse) | | How the createWebSocket helper coordinates full-duplex WebSocket connections across differing runtime engines like Bun, Deno, and Cloudflare. | [WebSocket Support](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/websocket-support) | | How hono/ssg traverses registered routes, runs pre-render plugins, and outputs pre-rendered static HTML and asset files to disk. | [Static Site Generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation) | | How serve-static middleware handles path rewriting, MIME type resolution, directory index fallback, and asset streaming across environments. | [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving) | | How testClient and inspection utilities in hono/testing and hono/dev assist in route introspection, handler profiling, and unit testing apps. | [Testing and Dev Tools](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/testing-and-dev-tools) | | How low-level shared helpers parse cookies, manage HTML escaping, encode URLs, handle concurrent execution, and resolve HTTP status codes. | [Utilities and Encoding](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/utilities-and-encoding) | ## Related - [Quick Start](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/quick-start) - [Project Structure](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/project-structure) - [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) --- ## Technical docs: Quick Start URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/quick-start
Relevant source files The following files were used as context for generating this wiki page: - [src/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [jsr.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [src/adapter/netlify/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/index.ts) - [src/helper/dev/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/dev/index.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts) - [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts) - [src/adapter/deno/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts) - [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts) - [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts) - [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts) - [src/adapter/bun/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts) - [src/adapter/aws-lambda/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/index.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [src/adapter/cloudflare-workers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/index.ts) - [src/adapter/lambda-edge/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/index.ts) - [src/helper/ssg/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/index.ts) - [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts)
## Overview Hono is a web framework built on Web Standards that provides a fast, lightweight core for building applications capable of running across multiple serverless and edge environments. Designed around standard `Request` and `Response` objects, Hono applications instantiate via the central [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) and [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) modules, exporting a default fetch handler or entry point. Runtime-specific execution details are bridged through dedicated [Runtime Adapters](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/runtime-adapters), allowing developers to deploy unified application logic onto targets ranging from serverless functions to edge runtimes while configuring tailored performance profiles with alternative routing engines. Sources: [src/index.ts:4-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L4-L14) ## Minimal Web Standard Application Setup ### Core Application Entry Point Hono exports a primary `Hono` class from its root module that serves as the central constructor for building Web Standard-compliant applications. Instantiating `new Hono()` sets up an application instance capable of registering routes, defining middleware, and processing standard HTTP requests and responses. The root entry point also exposes a comprehensive set of TypeScript types and utility classes that support strict type-checking for request handlers, error handlers, and execution contexts across all supported environments. ```ts import { Hono } from 'hono' const app = new Hono() app.get('/', (c) => c.text('Hono!')) export default app ``` Sources: [src/index.ts:7-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L7-L14) ### Exported Public Types and Classes The public API surface exported from the main entry point provides access to core structural classes and type definitions required for robust application development. These exports allow developers to explicitly type custom environment variables, request parameters, response payloads, and handler signatures. | Export Symbol | Category | Description | | :--- | :--- | :--- | | `Hono` | Class | Central application instance for routing and method registration | | `Context` | Class | Encapsulates request, response, and environment bindings | | `Env`, `Input`, `Schema` | Type | Type definitions for environment bindings and request validation inputs | | `Handler`, `MiddlewareHandler` | Type | Function signatures for route handlers and middleware execution | | `HonoRequest` | Type | Wrapper type representing incoming request properties and accessors | Sources: [src/index.ts:22-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L22-L53) > [!NOTE] > The root export module provides both runtime components like `Hono` and `Context` alongside pure TypeScript type declarations, ensuring complete type safety without adding runtime overhead to production builds. > Sources: [src/index.ts:22-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L22-L53) ## Handling Requests Across Environments ### Runtime Identification and Environment Access Hono provides adapter helper utilities in `src/helper/adapter/index.ts` to identify the current execution runtime and access environment variables portably across different hosting targets. The `getRuntimeKey()` function inspects `globalThis`, platform-specific user agent strings, and process properties to return a specific runtime string literal. Supported runtime targets and their identification identifiers include: | Runtime Key | Detection Mechanism | Environment Source | | :--- | :--- | :--- | | `node` | `global.process.release.name === 'node'` or user agent `Node.js` | `global.process.env` | | `deno` | User agent `Deno` | `Deno.env.toObject()` | | `bun` | User agent `Bun` | `global.process.env` | | `workerd` | User agent `Cloudflare-Workers` | `c.env` (Execution Context bindings) | | `edge-light` | `global.EdgeRuntime` string presence | `global.process.env` | | `fastly` | `global.fastly` definition | `{}` (ConfigStore usage) | | `other` | Fallback when no runtime matches | `{}` | Sources: [src/helper/adapter/index.ts:8-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L8-L48) Sources: [src/helper/adapter/index.ts:50-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L50-L90) > [!NOTE] > The `env()` helper function accepts an optional `runtime` override parameter. If omitted, it automatically invokes `getRuntimeKey()` to resolve the appropriate environment handler from `runtimeEnvHandlers`. > Sources: [src/helper/adapter/index.ts:10-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L10-L41) ### Portable Environment Variable Retrieval Using `env(c)` abstracts away differences between process-based global variables and request-scoped execution context bindings. For example, a Cloudflare Workers deployment accesses environment bindings directly from `c.env`, whereas Node, Bun, and Edge Light extract variables from `process.env`. ```ts import { env, getRuntimeKey } from '../../src/helper/adapter' import { Hono } from '../../src/hono' const app = new Hono() app.get('/', (c) => c.text(`Hello from ${getRuntimeKey()}`)) app.get('/env', (c) => { const { NAME } = env<{ NAME: string }>(c) return c.text(NAME) }) export default app ``` Sources: [runtime-tests/workerd/index.ts:2-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts#L2-L13) > [!WARNING] > Node versions prior to v21.1.0 do not support `navigator.userAgent`. The runtime detector falls back to checking `global.process.release.name === 'node'` when user agent detection is unavailable. > Sources: [src/helper/adapter/index.ts:54-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L54-L80) ## Configuring Serverless AWS Lambda Handlers ### Standard Lambda Events and Function Handlers Hono adapts standard applications for serverless execution through its AWS Lambda adapter modules. The core handler accepts events from multiple Amazon Web Services event sources, including API Gateway (v1 proxy events and v2 HTTP API payloads), Application Load Balancers (ALB), and direct Lambda Function URLs via `LambdaEvent` union types. ```ts import { Hono } from 'hono' import { handle } from 'hono/aws-lambda' const app = new Hono() app.get('/', (c) => c.text('Hello from Lambda')) app.get('/json', (c) => c.json({ message: 'Hello JSON' })) export const handler = handle(app) ``` Sources: [src/adapter/aws-lambda/handler.ts:211-222](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L211-L222) > [!NOTE] > When executing through `streamHandle`, Hono uses AWS Lambda's response streaming capability via `awslambda.streamifyResponse`. This requires `responseStream` wrapping with `awslambda.HttpResponseStream.from` to pipe chunks directly from the application's `ReadableStream`. > Sources: [src/adapter/aws-lambda/handler.ts:145-184](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L145-L184) ### Lambda@Edge Event Processing For content delivery network integrations, Hono provides a separate handler tailored for CloudFront Lambda@Edge events. The `handle` function unpacks `CloudFrontEdgeEvent` records, maps request headers and URIs, populates global `crypto`, and serializes responses back into CloudFront-compatible structures. | Event Type | Record Structure | Key Fields | Result Format | | :--- | :--- | :--- | :--- | | `CloudFrontEdgeEvent` | `event.Records[0].cf` | `config`, `request`, `response` | `CloudFrontResult` | | `LambdaEvent` | `APIGatewayProxyEvent` | `httpMethod`, `path`, `headers` | `APIGatewayProxyResult` | | `APIGatewayProxyEventV2` | `ApiGatewayRequestContextV2` | `rawPath`, `rawQueryString`, `cookies` | `APIGatewayProxyResult` | | `ALBProxyEvent` | `ALBRequestContext` | `httpMethod`, `queryStringParameters` | `APIGatewayProxyResult` | | `LatticeProxyEventV2` | `LatticeRequestContextV2` | `path`, `method`, `isBase64Encoded` | `APIGatewayProxyResult` | Sources: [src/adapter/aws-lambda/handler.ts:23-97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L23-L97) Sources: [src/adapter/lambda-edge/handler.ts:69-79](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L69-L79) Sources: [src/adapter/lambda-edge/handler.ts:88-99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L88-L99) > [!WARNING] > Binary response payloads in Lambda@Edge require explicit base64 encoding determined by `isContentTypeBinary`. Text-based content types such as plain text, HTML, CSS, JavaScript, and JSON are transmitted as raw strings, while others undergo base64 transformation. > Sources: [src/adapter/lambda-edge/handler.ts:140-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L140-L150) ## Deploying on Edge Cloud Handlers ### Cloudflare Pages Request and Middleware Handlers Hono provides integration adapters for edge environments, specifically targeting Cloudflare Pages and Vercel serverless functions. The Cloudflare Pages adapter exposes `handle` to wrap a Hono application into a `PagesFunction` that receives an `EventContext` containing the incoming `request`, execution environment bindings including `ASSETS`, and router `params`. ```ts import { Hono } from 'hono' import { handle } from 'hono/cloudflare-pages' const app = new Hono() app.get('/api/hello', (c) => c.text('Hello from Cloudflare Pages')) export const onRequest = handle(app) ``` Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46) > [!NOTE] > The `handleMiddleware` utility translates Hono middleware into Cloudflare Pages functions, constructing a Hono `Context` object where `executionCtx` holds the `EventContext` and `env` includes `eventContext` alongside user-defined bindings. > Sources: [src/adapter/cloudflare-pages/handler.ts:49-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L49-L65) ### Static Asset Serving and Vercel Integration For advanced Cloudflare Pages mode, `serveStatic` provides a middleware handler that delegates missing route requests to the Cloudflare `ASSETS` fetcher, returning a `404` status via `c.notFound()` when static assets cannot be resolved. Meanwhile, the Vercel adapter provides a streamlined `handle` function that directly passes the standard `Request` object to `app.fetch` without extra wrapper overhead. | Adapter Module | Exported Function | Target Environment | Core Parameter Structure | | :--- | :--- | :--- | :--- | | `hono/cloudflare-pages` | `handle` | Cloudflare Pages | `app: Hono` | | `hono/cloudflare-pages` | `handleMiddleware` | Cloudflare Pages Functions | `middleware: MiddlewareHandler` | | `hono/cloudflare-pages` | `serveStatic` | Cloudflare Pages Advanced Mode | none | | `hono/vercel` | `handle` | Vercel Serverless Functions | `app: Hono` | Sources: [src/adapter/cloudflare-pages/handler.ts:32-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L35) Sources: [src/adapter/cloudflare-pages/handler.ts:49-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L49-L59) Sources: [src/adapter/cloudflare-pages/handler.ts:114-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L114-L115) Sources: [src/adapter/vercel/handler.ts:4-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts#L4-L6) > [!WARNING] > When `handleMiddleware` catches an error inside middleware execution, instances of `HTTPException` are intercepted to automatically output their configured response via `context.error.getResponse()`. > Sources: [src/adapter/cloudflare-pages/handler.ts:80-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L80-L94) ## Selecting Lightweight Router Engines ### Alternative Routing Modules Hono provides modular routing implementations to fit varied performance and deployment profiles. Developers can select specific routing engines depending on whether bundle size minimization or advanced pattern matching is required. Sources: [src/router/linear-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts#L1-L6) ### Router Class Architecture | Router Module | Exported Class | Primary Engine Characteristics | | :--- | :--- | :--- | | `src/router/linear-router/index.ts` | `LinearRouter` | Linear iteration matching suited for minimal overhead | | `src/router/smart-router/index.ts` | `SmartRouter` | Dynamic selection router adapting to route patterns | | `src/router/pattern-router/index.ts` | `PatternRouter` | Pattern-based matching router for advanced expressions | Sources: [src/router/smart-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts#L1-L6) Sources: [src/router/pattern-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts#L1-L6) > [!NOTE] > `SmartRouter` inspects registered route definitions at initialization time to determine the optimal underlying strategy for request matching. > Sources: [src/router/smart-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts#L1-L6) ## Related - [Overview](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/overview) - [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) --- ## Technical docs: Project Structure URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/project-structure
Relevant source files The following files were used as context for generating this wiki page: - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/jsx/jsx-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts) - [jsr.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json) - [src/jsx/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/index.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/adapter/netlify/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/index.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts) - [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts) - [src/middleware/language/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/index.ts) - [src/adapter/netlify/mod.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/mod.ts) - [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts) - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [src/adapter/bun/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts) - [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [vitest.config.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/vitest.config.ts) - [src/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts) - [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts) - [src/helper/ssg/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/index.ts) - [src/jsx/dom/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/index.ts) - [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts) - [src/jsx/base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts) - [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts) - [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts) - [src/jsx/dom/jsx-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-runtime.ts) - [src/middleware/request-id/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [tsconfig.spec.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/tsconfig.spec.json)
## Overview The repository structure of Hono organizes its codebase around clear boundaries for core application logic, execution contexts, platform-specific [runtime adapters](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/runtime-adapters), pluggable routers, and dual-runtime JSX rendering. Top-level configuration files such as `package.json` and `jsr.json` establish dual distribution metadata for both npm and [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds), mapping fine-grained export subpaths across utilities, helpers, middleware, and adapters. Sources: [package.json:119-276](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L119-L276), [jsr.json:1-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L1-L106) ## Top-level directory layout ### Dual Distribution and Package Metadata Hono uses dual publishing configuration formats via package.json and `jsr.json` at the repository root, ensuring compatibility across both the npm ecosystem and the JSR registry. The JSR manifest defines package identification under `@hono/hono` at version `0.0.0`, configures compiler options targeting `["dom", "dom.iterable", "deno.ns"]`, and enables unstable features including `sloppy-imports`. Its publication filter explicitly includes `jsr.json`, `LICENSE`, `README.md`, and all TypeScript files under `src/**/*.ts`, while excluding test suites matching `src/**/*.test.ts` and `src/**/*.test.tsx`. ```json { "name": "@hono/hono", "version": "0.0.0", "compilerOptions": { "lib": ["dom", "dom.iterable", "deno.ns"] }, "unstable": ["sloppy-imports"] } ``` Sources: [jsr.json:1-110](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L1-L110) > [!NOTE] > The JSR configuration directly references source TypeScript files within `src/` as entrypoints, whereas the npm distribution targets compiled output artifacts located under `dist/`. ### Export Subpath Mapping Export mappings link fine-grained module subpaths to specific build targets for dual packaging. The npm distribution points conditional exports (`types`, `import`, `require`) to compiled output files under `./dist/`, while `jsr.json` maps identical subpaths directly to their corresponding TypeScript source modules under `./src/`. | Subpath Identifier | JSR Source Target | npm Import Target | npm Require Target | | :--- | :--- | :--- | :--- | | `.` | `./src/index.ts` | `./dist/index.js` | `./dist/cjs/index.js` | | `./tiny` | `./src/preset/tiny.ts` | `./dist/preset/tiny.js` | `./dist/cjs/preset/tiny.js` | | `./quick` | `./src/preset/quick.ts` | `./dist/preset/quick.js` | `./dist/cjs/preset/quick.js` | | `./router` | `./src/router.ts` | `./dist/router.js` | `./dist/cjs/router.js` | | `./client` | `./src/client/index.ts` | `./dist/client/index.js` | `./dist/cjs/client/index.js` | Sources: [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106), [package.json:119-276](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L119-L276) > [!WARNING] > Modifying root export paths requires synchronized updates across both `jsr.json` and `package.json` to prevent broken module resolution in either the npm or JSR distribution channels. ### Compiler Configuration and Test Spec TypeScript compilation for tests is governed by `tsconfig.spec.json`, which extends `./tsconfig.base.json`. It configures JSX compilation via `"jsx": "react-jsx"`, sets the JSX import source to `"hono/jsx"`, suppresses output emission with `"noEmit": true`, restricts the root directory to `./src`, and injects `"vitest/globals"` into the type definitions while including source files and `src/middleware/jwk/keys.test.json`. ```json { "extends": "./tsconfig.base.json", "compilerOptions": { "jsx": "react-jsx", "jsxImportSource": "hono/jsx", "noEmit": true, "rootDir": "./src", "types": ["vitest/globals"] }, "include": ["src", "src/middleware/jwk/keys.test.json"] } ``` Sources: [tsconfig.spec.json:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/tsconfig.spec.json#L1-L11) ## Source tree architecture ### Core Engine and Entrypoints The main entry point for the framework is defined in `src/index.ts`, which exports the primary Hono application class alongside essential types and abstractions. Core framework primitives are exported directly from their respective internal modules, including `Context`, `HonoRequest`, and type definitions covering environment variables, error handlers, handlers, middleware handlers, request/response inference types, and input definitions. ```typescript import { Hono } from './hono' /** * Types for environment variables, error handlers, handlers, middleware handlers, and more. */ export type { Env, ErrorHandler, Handler, MiddlewareHandler, Next, NotFoundResponse, NotFoundHandler, Input, } from './types' /** * Types for context, context variable map, context renderer, and execution context. */ export { Context } from './context' export type { ContextVariableMap, ContextRenderer, ExecutionContext } from './context' /** * Type for HonoRequest. */ export type { HonoRequest } from './request' /** * Types for inferring request and response types and client request options. */ export type { InferRequestType, InferResponseType, ClientRequestOptions } from './client' /** * Hono framework for building web applications. */ export { Hono } ``` Sources: [src/index.ts:17-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L17-L53) > [!NOTE] > `src/index.ts` serves as the root public API facade for consumers importing from the main package specifier, cleanly separating engine internals from public type definitions and helper interfaces. ### Internal Module Boundaries The `src/` directory isolates core routing engine code, request-response execution handling, middleware implementations, helper utilities, and platform adapters into dedicated boundaries. Package exports map fine-grained features such as middleware for CORS, CSRF, JWT validation, ETag generation, security headers, and logging directly to their corresponding subdirectories within `src/`. | Export Subpath | Source Module Target | Core Domain | | :--- | :--- | :--- | | `./cors` | `./src/middleware/cors/index.ts` | Middleware | | `./csrf` | `./src/middleware/csrf/index.ts` | Middleware | | `./jwt` | `./src/middleware/jwt/index.ts` | Middleware | | `./etag` | `./src/middleware/etag/index.ts` | Middleware | | `./logger` | `./src/middleware/logger/index.ts` | Middleware | | `./request-id` | `./src/middleware/request-id/index.ts` | [Request ID and Language](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/request-id-and-language) | | `./language` | `./src/middleware/language/index.ts` | [Request ID and Language](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/request-id-and-language) | | `./ssg` | `./src/helper/ssg/index.ts` | [Static Site Generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation) | Sources: [package.json:123-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L123-L272) ## Router implementation subdirectories ### Specialized Routing Engines Hono isolates its routing algorithms into dedicated subdirectories under `src/router/`, exposing distinct strategies for route compilation and matching. Each specialized router package exports its engine class via its entry point module. Sources: [src/router/reg-exp-router/index.ts:1-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts#L1-L7) ### RegExpRouter and Preparation Helpers The `reg-exp-router` implementation exports both `RegExpRouter` and preparation utilities like `PreparedRegExpRouter`, `buildInitParams`, and `serializeInitParams`. Sources: [src/router/reg-exp-router/index.ts:6-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts#L6-L7) > [!TIP] > Use `PreparedRegExpRouter` alongside `buildInitParams` and `serializeInitParams` when pre-compiling regular expression routing tables to bypass runtime regex construction overhead in cold-start environments. ### Trie, Smart, and Linear Routers Additional router implementations include `TrieRouter`, `SmartRouter`, and `LinearRouter`, each exported from its respective subdirectory. Sources: [src/router/trie-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts#L1-L6), [src/router/smart-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts#L1-L6), [src/router/linear-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts#L1-L6) > [!NOTE] > `SmartRouter` inspects registered routes at initialization time to automatically select the optimal underlying router implementation based on pattern complexity. ## Platform adapter organization ### Handler Bindings and Asset Serving Runtime integration modules inside `src/adapter/` map native platform request events and environment bindings to the framework's core request-response cycle. For Cloudflare Pages, `handle` converts incoming `EventContext` payloads into `app.fetch` invocations, injecting `eventContext` into environment bindings alongside `waitUntil` and `passThroughOnException` lifecycle controls. ```typescript export const handle = ( app: Hono ): PagesFunction => (eventContext) => { return app.fetch( eventContext.request, { ...eventContext.env, eventContext }, { waitUntil: eventContext.waitUntil, passThroughOnException: eventContext.passThroughOnException, props: {}, } ) } ``` Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46) > [!NOTE] > `handleMiddleware` in the Cloudflare Pages adapter constructs a Hono `Context` with an expanded environment object containing the full [execution context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context), wrapping incoming `next()` calls and catching `HTTPException` instances to format native `Response` outputs. Advanced Pages configurations utilize `serveStatic`, which queries the `ASSETS` fetcher binding directly from the environment and triggers `c.notFound()` when asset requests return a `404` status code. ```typescript export const serveStatic = (): MiddlewareHandler => { return async (c) => { const env = c.env as { ASSETS: FetcherLike } const res = await env.ASSETS.fetch(c.req.raw) if (res.status === 404) { return c.notFound() } return res } } ``` Sources: [src/adapter/cloudflare-pages/handler.ts:114-123](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L114-L123) ### Connection Metadata and Target Exports Netlify deployment integration exports its request handler and connection information resolver through a unified adapter entry point module. | Adapter Module | Source Path | Exported Symbols | Target Environment | | :--- | :--- | :--- | :--- | | `netlify` | `src/adapter/netlify/mod.ts` | `handle`, `getConnInfo` | Netlify Functions / Edge | | `cloudflare-pages` | `src/adapter/cloudflare-pages/handler.ts` | `handle`, `handleMiddleware`, `serveStatic` | Cloudflare Pages | Sources: [src/adapter/netlify/mod.ts:1-2](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/mod.ts#L1-L2), [src/adapter/cloudflare-pages/handler.ts:32-123](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L123) > [!TIP] > Platform-specific adapters keep framework core logic decoupled from vendor request types by normalizing incoming platform events directly into standard `Request` objects before handing execution over to Hono. ## Client JSX subtrees ### DOM and Client Runtime Organization Hono partitions its JSX rendering engine into distinct server-side string serialization paths and client-side browser DOM execution subtrees. The client DOM runtime modules reside under `src/jsx/dom/`, providing browser-native rendering mechanisms, interactive hooks like `useState` and `useEffect`, and dedicated package exports in `package.json`. ```typescript export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime' export { jsxDEV as jsxs } from './jsx-dev-runtime' export type { JSX } from './jsx-dev-runtime' ``` Sources: [src/jsx/dom/jsx-runtime.ts:6-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-runtime.ts#L6-L8) > [!NOTE] > The `hono/jsx/dom/jsx-runtime` module re-exports `jsxDEV` under both `jsx` and `jsxs` identifiers alongside `Fragment` and the `JSX` type definitions to satisfy compiler transform requirements for interactive client components. ### Subtree Package Exports Export definitions in `package.json` expose specialized subpath entries for server-side JSX helpers, streaming renderers, and client-side DOM bundles. | Subpath Entry | Types Declaration | ESM Import Target | CommonJS Require Target | | :--- | :--- | :--- | :--- | | `./jsx` | `./dist/types/jsx/index.d.ts` | `./dist/jsx/index.js` | `./dist/cjs/jsx/index.js` | | `./jsx/jsx-runtime` | `./dist/types/jsx/jsx-runtime.d.ts` | `./dist/jsx/jsx-runtime.js` | `./dist/cjs/jsx/jsx-runtime.js` | | `./jsx/streaming` | `./dist/types/jsx/streaming.d.ts` | `./dist/jsx/streaming.js` | `./dist/cjs/jsx/streaming.js` | | `./jsx/dom` | `./dist/types/jsx/dom/index.d.ts` | `./dist/jsx/dom/index.js` | `./dist/cjs/jsx/dom/index.js` | | `./jsx/dom/jsx-runtime` | `./dist/types/jsx/dom/jsx-runtime.d.ts` | `./dist/jsx/dom/jsx-runtime.js` | `./dist/cjs/jsx/dom/jsx-runtime.js` | | `./jsx/dom/client` | `./dist/types/jsx/dom/client.d.ts` | `./dist/jsx/dom/client.js` | `./dist/cjs/jsx/dom/client.js` | | `./jsx/dom/css` | `./dist/types/jsx/dom/css.d.ts` | `./dist/jsx/dom/css.js` | `./dist/cjs/jsx/dom/css.js` | | `./jsx/dom/server` | `./dist/types/jsx/dom/server.d.ts` | `./dist/jsx/dom/server.js` | `./dist/cjs/jsx/dom/server.js` | Sources: [package.json:153-207](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L153-L207) > [!TIP] > Use hono/jsx/dom/client when mounting interactive component trees on browser targets, while keeping server-rendered templates decoupled by utilizing hono/jsx or hono/jsx-renderer. ## Related - [Overview](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/getting-started/overview) - [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds) --- ## Technical docs: Application Core URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core
Relevant source files The following files were used as context for generating this wiki page: - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts) - [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts)
## Overview The application core of Hono centers around the `Hono` class and its foundational base `HonoBase` in `[[Application Core]]`, serving as the central dispatcher and routing engine that handles [request lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle) execution, path matching, and middleware coordination across Web Standard runtimes. By separating core routing logic from distribution builds like `[[Presets and Builds]]`, Hono provides an extensible architecture where applications can inject optimized routing strategies such as `SmartRouter`, `TrieRouter`, `LinearRouter`, or `PatternRouter` to resolve endpoints and parameters. Incoming requests are wrapped into an [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) via `Context` and `HonoRequest` objects, which manage response rendering, environment bindings, and scoped basePath transformations while supporting modular sub-application composition and centralized error handling. Sources: [src/hono-base.ts:98-126](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L98-L126), [src/hono.ts:16-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts#L16-L33), [src/context.ts:293-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L361), [src/request.ts:36-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L36-L80) ## Hono and HonoBase architecture ### Class Hierarchy and Core Separation The application architecture relies on a two-tier class hierarchy separating abstract routing mechanisms from concrete router initialization. `HonoBase` acts as an abstract-like engine implementing route registration, method assignment, [middleware composition](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/middleware-composition), request dispatching, and error handling without binding itself to a specific router implementation. The concrete `Hono` class extends `HonoBase`, supplying default router configurations and initializing application options. ```typescript class Hono< E extends Env = Env, S extends Schema = {}, BasePath extends string = '/', CurrentPath extends string = BasePath, > { get!: HandlerInterface post!: HandlerInterface put!: HandlerInterface delete!: HandlerInterface options!: HandlerInterface patch!: HandlerInterface all!: HandlerInterface on: OnHandlerInterface use: MiddlewareHandlerInterface /* This class is like an abstract class and does not have a router. To use it, inherit the class and implement router in the constructor. */ router!: Router<[H, RouterRoute]> readonly getPath: GetPath // Cannot use `#` because it requires visibility at JavaScript runtime. private _basePath: string = '/' #path: string = '/' routes: RouterRoute[] = [] constructor(options: HonoOptions = {}) { ``` Sources: [src/hono-base.ts:98-126](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L98-L126) ```typescript export class Hono< E extends Env = BlankEnv, S extends Schema = BlankSchema, BasePath extends string = '/', > extends HonoBase { /** * Creates an instance of the Hono class. * * @param options - Optional configuration options for the Hono instance. */ constructor(options: HonoOptions = {}) { super(options) this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()], }) } ``` Sources: [src/hono.ts:16-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts#L16-L33) > [!NOTE] > `HonoBase` declares `router` without instantiating it directly in its own constructor. Subclasses or custom builds must inject a valid `Router` implementation before routing requests, or errors will occur during matching. ### Constructor Options and Router Injection The constructor accepts configuration options via `HonoOptions`, allowing developers to override default path resolution strategies or inject custom routing engines that conform to the [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) specification. | Option Key | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `router` | `Router<[H, RouterRoute]>` | `new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()] })` | Custom router instance injected into the application. | | `strict` | `boolean` | `true` | Controls whether trailing slashes are strictly matched during path resolution. | | `getPath` | `GetPath` | `getPath` (strict) or `getPathNoStrict` | Custom function to extract the pathname from incoming request objects. | ```typescript const { strict, ...optionsWithoutStrict } = options Object.assign(this, optionsWithoutStrict) this.getPath = (strict ?? true) ? (options.getPath ?? getPath) : getPathNoStrict } ``` Sources: [src/hono-base.ts:170-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L170-L173) ```typescript constructor(options: HonoOptions = {}) { super(options) this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()], }) } ``` Sources: [src/hono.ts:26-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts#L26-L33) > [!TIP] > Setting `strict: false` in `HonoOptions` automatically swaps the default path parser from `getPath` to `getPathNoStrict`, allowing requests with and without trailing slashes to resolve to the same handler. ### Default Router Configuration When instantiated without parameters, the concrete `Hono` constructor defaults to `SmartRouter`, configured with an internal fallback array containing `RegExpRouter` and `TrieRouter` instances. This composition allows Hono to dynamically evaluate route patterns and delegate matching to the most efficient underlying router strategy. ```typescript constructor(options: HonoOptions = {}) { super(options) this.router = options.router ?? new SmartRouter({ routers: [new RegExpRouter(), new TrieRouter()], }) } ``` Sources: [src/hono.ts:26-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts#L26-L33) ## HTTP method handler registration ### Method and Route Registration APIs The `HonoBase` class exposes standard HTTP method registration properties including `get`, `post`, `put`, `delete`, `options`, `patch`, and `all`. Each method is initialized dynamically in the constructor by iterating over `METHODS` and `METHOD_NAME_ALL_LOWERCASE`. When invoked, these method properties accept either a path string followed by one or more request handlers, or simply a sequence of handlers when a path has been set previously. ```typescript const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE] allMethods.forEach((method) => { this[method] = (args1: string | H, ...args: H[]) => { if (typeof args1 === 'string') { this.#path = args1 } else { this.#addRoute(method, this.#path, args1) } args.forEach((handler) => { this.#addRoute(method, this.#path, handler) }) return this as any } }) ``` Sources: [src/hono-base.ts:128-141](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L128-L141) > [!NOTE] > If the first argument passed to a method handler like `app.get()` is a string, it updates the internal `#path` property for that registration context. Subsequent arguments and subsequent calls without a string path attach the provided handlers to that stored path. ### Custom Method Registration via app.on In addition to standard method shortcuts, `HonoBase` provides the `.on()` method to register routes for arbitrary HTTP methods or collections of methods and paths simultaneously. The `.on()` implementation flattens input arrays for both paths and methods, converting method strings to uppercase via `.toUpperCase()` before adding them to the underlying router. ```typescript // Implementation of app.on(method, path, ...handlers[]) this.on = (method: string | string[], path: string | string[], ...handlers: H[]) => { for (const p of [path].flat()) { this.#path = p for (const m of [method].flat()) { handlers.map((handler) => { this.#addRoute(m.toUpperCase(), this.#path, handler) }) } } return this as any } ``` Sources: [src/hono-base.ts:143-154](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L143-L154) > [!WARNING] > Passing lowercase method strings to `app.on()` is automatically normalized via `toUpperCase()`, but callers must ensure custom method identifiers comply with valid HTTP specification requirements if used outside standard fetch client constraints. ### Type Signatures and Handler Overloads Type safety across route registration is governed by `HandlerInterface` and `OnHandlerInterface`, which support multiple overloaded signatures ranging from single handlers to multi-handler middleware chains up to ten handlers deep. These interfaces track environment variables (`Env`), path parameters, input schemas (`Input`), and typed response mappings (`HandlerResponse`), merging them into the application's aggregate `Schema`. ```typescript MiddlewareHandler, MiddlewareHandler, MiddlewareHandler, MiddlewareHandler, MiddlewareHandler, ] ): HonoBase< IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>, S, BasePath, MergedPath > //// app.use(path, ...handlers[])

( path: P, ...handlers: MiddlewareHandler>[] ): HonoBase> } ``` Sources: [src/types.ts:1431-1449](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts:1431-1449) ```typescript M5 extends H = H, M6 extends H = H, M7 extends H = H, M8 extends H = H, M9 extends H = H, >( method: M, path: P, ...handlers: [ H & M1, H & M2, H & M3, H & M4, H & M5, H & M6, H & M7, H & M8, H & M9, H, ] ): HonoBase< IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>, S & ToSchema< M, MergePath, I10, | MergeTypedResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse | MergeMiddlewareResponse >, BasePath, MergePath > ``` Sources: [src/types.ts:1901-1941](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts:1901-1941) ## Route storage and path resolution ### Internal Route Structure and Routing Tables When handlers are registered through method shortcuts, `app.use()`, or `app.on()`, `HonoBase` invokes its private `#addRoute` method to normalize paths, uppercase method identifiers, and populate internal routing structures. Every registered route is encapsulated as a `RouterRoute` object containing the assigned `basePath`, the fully qualified `path`, the HTTP `method`, and the target `handler`. ```typescript #addRoute(method: string, path: string, handler: H, baseRoutePath?: string): void { method = method.toUpperCase() path = mergePath(this._basePath, path) const r: RouterRoute = { basePath: baseRoutePath !== undefined ? mergePath(this._basePath, baseRoutePath) : this._basePath, path, method, handler, } this.router.add(method, path, [handler, r]) this.routes.push(r) } ``` Sources: [src/hono-base.ts:385-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L385-L397) The `RouterRoute` entries are dual-stored: they are pushed sequentially into the instance's public `routes` array for introspection or sub-application composition, and they are registered directly into the active `router` instance by calling `this.router.add(method, path, [handler, r])`. This associates each route pattern with a tuple containing the handler and its metadata description. ```source src/hono-base.ts:124| routes: RouterRoute[] = [] ``` Sources: [src/hono-base.ts:124](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L124) > [!NOTE] > The router implementation stores tuples of `[handler, r]` as values for each registered method and path combination, permitting downstream dispatch logic to access both the executable function and the complete `RouterRoute` descriptor during request matching. ### Path Normalization and Prefix Merging Path normalization and prefix combining are handled by utility functions imported from `./utils/url`, specifically `mergePath`, `getPath`, and `getPathNoStrict`. Within `#addRoute`, incoming paths are passed through `mergePath(this._basePath, path)` to ensure that any configured application base path prefixes are correctly prepended without redundant slashes or missing separators. ```typescript method = method.toUpperCase() path = mergePath(this._basePath, path) ``` Sources: [src/hono-base.ts:386-387](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L386-L387) The active `getPath` function is selected during instantiation based on the `strict` option flag. If `strict` evaluates to true (the default), `options.getPath ?? getPath` is selected, enforcing exact path matching including trailing slashes. If `strict` is set to false, `getPathNoStrict` is assigned to normalize out trailing slashes during path resolution. ```typescript const { strict, ...optionsWithoutStrict } = options Object.assign(this, optionsWithoutStrict) this.getPath = (strict ?? true) ? (options.getPath ?? getPath) : getPathNoStrict } ``` Sources: [src/hono-base.ts:170-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L170-L173) > [!CAUTION] > Modifying the `strict` flag alters how `getPath` processes incoming URLs at runtime; mixing strict and non-strict sub-applications without accounting for trailing slash normalization can lead to unexpected `404 Not Found` responses during lookup matching. ## Sub-application routing and basePath ### Scoped basePath Cloning and Instance Isolation Modular composition in Hono relies on creating isolated sub-applications and scoping routing prefixes via `.basePath()`. The `.basePath()` method invokes a private `#clone()` helper that instantiates a new Hono instance sharing the parent's underlying `router`, `getPath`, `errorHandler`, `#notFoundHandler`, and `routes` references, while updating the private `_basePath` property through `mergePath(this._basePath, path)`. ```typescript #clone(): Hono { const clone = new Hono({ router: this.router, getPath: this.getPath, }) clone.errorHandler = this.errorHandler clone.#notFoundHandler = this.#notFoundHandler clone.routes = this.routes return clone } ``` Sources: [src/hono-base.ts:175-184](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L175-L174) ```typescript basePath( path: SubPath ): Hono, MergePath> { const subApp = this.#clone() subApp._basePath = mergePath(this._basePath, path) return subApp } ``` Sources: [src/hono-base.ts:247-253](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L247-L253) > [!TIP] > Calling `.basePath()` does not duplicate the underlying router or existing route collection; instead, it returns a lightweight shadow instance pre-configured with an extended `_basePath` value for subsequent route registrations. ### Composing Sub-Applications with route() Sub-applications and independent Hono router instances can be merged into a parent application using the `.route()` method. When `.route(path, app)` is invoked, it creates a scoped sub-application at the specified mount path and iterates over all `app.routes` definitions, re-registering each route into the parent's router and route collection. ```typescript route< SubPath extends string, SubEnv extends Env, SubSchema extends Schema, SubBasePath extends string, SubCurrentPath extends string, >( path: SubPath, app: Hono ): Hono> | S, BasePath, CurrentPath> { const subApp = this.basePath(path) app.routes.map((r) => { let handler if (app.errorHandler === errorHandler) { handler = r.handler } else { handler = async (c: Context, next: Next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res ;(handler as any)[COMPOSED_HANDLER] = r.handler } subApp.#addRoute(r.method, r.path, handler, r.basePath) }) return this } ``` Sources: [src/hono-base.ts:208-232](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L208-L232) If the mounted sub-application defines a custom error handler differing from the default `errorHandler`, `.route()` wraps each copied route handler in a composed execution block that routes errors through the sub-application's specific error boundary before falling back or continuing execution. ```typescript if (app.errorHandler === errorHandler) { handler = r.handler } else { handler = async (c: Context, next: Next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res ;(handler as any)[COMPOSED_HANDLER] = r.handler } ``` Sources: [src/hono-base.ts:221-227](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L221-L227) ### External Framework Mounting with mount() External request handlers and applications built with other frameworks can be integrated into a Hono application using the `.mount()` method. It processes optional `MountOptions` configurations, which accept either a custom `MountOptionHandler` function or an options object containing an `optionHandler` and a `replaceRequest` strategy. ```typescript mount( path: string, applicationHandler: (request: Request, ...args: any) => Response | Promise, options?: MountOptions ): Hono { // handle options let replaceRequest: MountReplaceRequest | undefined let optionHandler: MountOptionHandler | undefined if (options) { if (typeof options === 'function') { optionHandler = options } else { optionHandler = options.optionHandler if (options.replaceRequest === false) { replaceRequest = (request) => request } else { replaceRequest = options.replaceRequest } } } ``` Sources: [src/hono-base.ts:328-347](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L328-L347) The request transformation and argument extraction behavior during execution depend on whether explicit options are provided: | Option Property | Default Behavior | Custom Behavior | | :--- | :--- | :--- | | `replaceRequest` | Strips the mounted path prefix from the incoming request URL pathname | Passes the request through a custom `MountReplaceRequest` function or preserves it unchanged if set to `false` | | `optionHandler` | Passes `[c.env, executionContext]` extracted from the active `Context` | Invokes the custom `MountOptionHandler` function and normalizes its return value into an array | ```typescript const getOptions: (c: Context) => unknown[] = optionHandler ? (c) => { const options = optionHandler!(c) return Array.isArray(options) ? options : [options] } : (c) => { let executionContext: ExecutionContext | undefined = undefined try { executionContext = c.executionCtx } catch {} // Do nothing return [c.env, executionContext] } replaceRequest ||= (() => { const mergedPath = mergePath(this._basePath, path) const pathPrefixLength = mergedPath === '/' ? 0 : mergedPath.length return (request) => { const url = new URL(request.url) url.pathname = this.getPath(request).slice(pathPrefixLength) || '/' return new Request(url, request) } })() ``` Sources: [src/hono-base.ts:350-370](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L350-L370) Once the request transformer and argument extractors are resolved, `.mount()` registers a wildcard route matching `mergePath(path, '*')` with `METHOD_NAME_ALL`, executing the external handler inside a middleware wrapper. ```typescript const handler: MiddlewareHandler = async (c, next) => { const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c)) if (res) { return res } await next() } this.#addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler) return this } ``` Sources: [src/hono-base.ts:372-383](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L372-L383) ## Application-level error handling ### Default Handlers and Customization Hono provides built-in fallback handlers for unhandled routing misses and runtime exceptions. The default `notFoundHandler` returns a plain text response with status code `404` and the body `404 Not Found`. ```typescript const notFoundHandler: NotFoundHandler = (c) => { return c.text('404 Not Found', 404) } ``` Sources: [src/hono-base.ts:31-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L31-L33) The default `errorHandler` inspects caught exceptions to check if they implement a `getResponse()` method. If present, it directly returns the response provided by the error instance; otherwise, it formats a generic internal error response. ```typescript const errorHandler: ErrorHandler = (err, c) => { if ('getResponse' in err) { const res = err.getResponse() return c.newResponse(res.body, res) } console.error(err) return c.text('Internal Server Error', 500) ``` Sources: [src/hono-base.ts:35-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L35-L41) Applications can override these default behaviors by registering custom handlers via the `.notFound()` and `.onError()` methods, which update the instance's `#notFoundHandler` and `errorHandler` properties and return the modified Hono instance. ```typescript onError = (handler: ErrorHandler): Hono => { this.errorHandler = handler return this } /** * `.notFound()` allows you to customize a Not Found Response. * * @see {@link https://hono.dev/docs/api/hono#not-found} * * @param {NotFoundHandler} handler - request handler for not-found * @returns {Hono} changed Hono instance * * @example * ```ts * app.notFound((c) => { * return c.text('Custom 404 Message', 404) * }) * ``` */ notFound = (handler: NotFoundHandler): Hono => { this.#notFoundHandler = handler return this } ``` Sources: [src/hono-base.ts:271-294](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L271-L294) ### Exception Dispatching and Error Normalization During request dispatching in `#dispatch()`, runtime exceptions thrown within route handlers or middleware are caught and passed to `#handleError()`. The `#handleError()` method checks if the thrown value is an instance of `Error`; if so, it delegates to the registered `errorHandler`. If the thrown value is not an `Error` instance, it rethrows the raw value. ```typescript #handleError(err: unknown, c: Context): Response | Promise { if (err instanceof Error) { return this.errorHandler(err, c) } throw err } ``` Sources: [src/hono-base.ts:399-404](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L399-L404) > [!WARNING] > Non-`Error` exceptions (such as thrown strings or primitives) bypass the custom `errorHandler` entirely and propagate out of `#handleError()`, potentially causing unhandled promise rejections if not caught at the top-level fetch boundary. When dispatching requests with a single matching handler or via composed middleware chains, exceptions originating from synchronous code execution, asynchronous promise rejections, or unfinalized context states are intercepted and routed through the error handling pipeline. ```typescript if (matchResult[0].length === 1) { let res: ReturnType try { res = matchResult[0][0][0][0](c, async () => { c.res = await this.#notFoundHandler(c) }) } catch (err) { return this.#handleError(err, c) } return res instanceof Promise ? res .then( (resolved: Response | undefined) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c)) ) .catch((err: Error) => this.#handleError(err, c)) : (res ?? this.#notFoundHandler(c)) } const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler) return (async () => { try { const context = await composed(c) if (!context.finalized) { throw new Error( 'Context is not finalized. Did you forget to return a Response object or `await next()`?' ) } return context.res } catch (err) { return this.#handleError(err, c) } })() } ``` Sources: [src/hono-base.ts:430-466](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L430-L466) ## Fetch interface and runtime execution ### Standard Fetch Handler and Request Dispatching The `.fetch()` method serves as the primary entry point for Hono applications, adhering to the standard Web Fetch API signature by accepting a `Request` object, optional environment bindings, and an `ExecutionContext`. It delegates directly to the private `#dispatch()` method using `request.method` and the provided bindings. ```typescript fetch: ( request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext ) => Response | Promise = (request, ...rest) => { return this.#dispatch(request, rest[1], rest[0], request.method) } ``` Sources: [src/hono-base.ts:479-485](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L479-L485) Inside `#dispatch()`, HTTP `HEAD` requests are intercepted and handled specially by delegating to a `GET` dispatch and stripping the response body, returning a new `Response` with a `null` body. ```typescript if (method === 'HEAD') { return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, 'GET')))() } ``` Sources: [src/hono-base.ts:413-416](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L413-L416) For all other methods, path resolution is performed via the configured `getPath` helper, and the router matches the method against the path to produce a `matchResult`. A new `Context` instance is then instantiated with the request, matched route handlers, bindings, and execution context. ```typescript const path = this.getPath(request, { env }) const matchResult = this.router.match(method, path) const c = new Context(request, { path, matchResult, env, executionCtx, notFoundHandler: this.#notFoundHandler, }) ``` Sources: [src/hono-base.ts:418-427](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L418-L427) > [!NOTE] > If a match yields exactly one handler, Hono bypasses the full `[[Middleware Composition|compose]]` pipeline overhead to execute the handler directly, falling back to the not-found handler if unfinalized. ```typescript // Do not `compose` if it has only one handler if (matchResult[0].length === 1) { let res: ReturnType try { res = matchResult[0][0][0][0](c, async () => { c.res = await this.#notFoundHandler(c) }) } catch (err) { return this.#handleError(err, c) } return res instanceof Promise ? res .then( (resolved: Response | undefined) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c)) ) .catch((err: Error) => this.#handleError(err, c)) : (res ?? this.#notFoundHandler(c)) } ``` Sources: [src/hono-base.ts:429-448](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L429-L448) When multiple handlers match, `#dispatch()` invokes `compose` with the matched handlers, error handler, and not-found handler, ensuring that context finalization invariants are strictly enforced on the resulting execution pipeline. ```typescript const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler) return (async () => { try { const context = await composed(c) if (!context.finalized) { throw new Error( 'Context is not finalized. Did you forget to return a Response object or `await next()`?' ) } return context.res } catch (err) { return this.#handleError(err, c) } })() } ``` Sources: [src/hono-base.ts:450-466](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L450-L466) ### Testing Helpers and Service Worker Integration Hono provides the `.request()` method as a utility primarily designed for testing. It accepts `Request`, string, or `URL` inputs along with optional request initialization options, environment bindings, and execution context, automatically resolving relative paths against a localhost base if necessary. ```typescript request = ( input: Request | string | URL, requestInit?: RequestInit, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext ): Response | Promise => { if (input instanceof Request) { return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx) } input = input.toString() return this.fetch( new Request( /^https?:\/\//.test(input) ? input : `http://localhost${mergePath('/', input)}`, requestInit ), Env, executionCtx ) } ``` Sources: [src/hono-base.ts:499-517](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L499-L517) For environments adhering to the Service Worker API (such as non-ES module Cloudflare Workers), the `.fire()` method registers a global `fetch` event listener via `addEventListener`, responding to incoming fetch events by invoking `#dispatch()`. ```typescript fire = (): void => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore addEventListener('fetch', (event: FetchEventLike): void => { event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method)) }) } ``` Sources: [src/hono-base.ts:536-542](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L536-L542) > [!WARNING] > The `.fire()` method is deprecated and should be avoided in modern ES module runtimes; use `fire` from `hono/service-worker` instead. ```typescript * @deprecated * Use `fire` from `hono/service-worker` instead. ``` Sources: [src/hono-base.ts:522-523](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L522-L523) ## Related - [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle) - [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) - [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) --- ## Technical docs: Request Lifecycle URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle

Relevant source files The following files were used as context for generating this wiki page: - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts) - [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts) - [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts) - [src/client/client.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/client/client.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts) - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/client/fetch-result-please.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/client/fetch-result-please.ts) - [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts) - [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts) - [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts) - [src/adapter/service-worker/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts) - [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts) - [src/http-exception.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts) - [src/request/constants.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request/constants.ts)
## Overview The request lifecycle governs how inbound HTTP requests flow through Hono, starting from native runtime objects or serverless gateway event wrappers src/adapter/aws-lambda/handler.ts:318-342, moving through path matching and src/hono-base.ts:418-428, and ending with response finalization or src/http-exception.ts:66-77. It provides the foundational mechanisms for encapsulating requests, lazily decoding bodies, extracting parameters, and managing errors across handlers src/request.ts:51-80, src/request.ts:220-239, src/request.ts:106-128. Sources: [src/hono-base.ts:418-428](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L418-L428), [src/request.ts:51-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L51-L80), [src/request.ts:106-128](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L106-L128), [src/request.ts:220-239](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L220-L239), [src/adapter/aws-lambda/handler.ts:318-342](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L318-L342), [src/http-exception.ts:66-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L66-L77) ## Incoming Web Request Encapsulation ### Request Instance Wrapper The `HonoRequest` class encapsulates standard Fetch `Request` objects, tying them to Hono's routing state, matched parameters, and path resolution. Its constructor accepts the underlying `Request`, an optional path string defaulting to `'/'`, and a match result tuple representing routing outcomes. ```typescript export class HonoRequest

{ raw: Request #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData #matchResult: Result<[unknown, RouterRoute]> routeIndex: number = 0 path: string bodyCache: BodyCache = {} constructor( request: Request, path: string = '/', matchResult: Result<[unknown, RouterRoute]> = [[]] ) { this.raw = request this.path = path this.#matchResult = matchResult this.#validatedData = {} } ... ``` Sources: [src/request.ts:36-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L36-L80) > [!NOTE] > The `routeIndex` property defaults to `0` and determines which matched route segment supplies the active path parameters when multiple sub-applications or nested router matches are evaluated. > Sources: [src/request.ts:55-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L55-L55) ### Symbol Constants and Metadata Hono exposes dedicated unique symbols to inspect internal request state, such as retrieving match results directly from handler contexts. | Symbol Constant | Type | Meaning / Purpose | | :--- | :--- | :--- | | `GET_MATCH_RESULT` | `unique symbol` | Symbol used to retrieve the internal route match result from request instances. | ```typescript export const GET_MATCH_RESULT: unique symbol = Symbol() ``` Sources: [src/request/constants.ts:1-1](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request/constants.ts#L1-L1) ## Body Parsing and Stream Buffering ### Lazy Caching and Payload Extraction The `HonoRequest` class implements a private `#cachedBody` method that manages lazy decoding and cached extraction of request payloads across different formats such as text, JSON, ArrayBuffer, Blob, and FormData. The `BodyCache` type defines the structure holding these cached payloads as partial properties matching the `Body` type definition. ```typescript type Body = { json: any text: string arrayBuffer: ArrayBuffer blob: Blob formData: FormData } type BodyCache = Partial ``` Sources: [src/request.ts:20-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L20-L27) > [!NOTE] > Request bodies can only be consumed once on standard Fetch `Request` objects. Hono avoids stream consumption errors by caching the result in `bodyCache` and deriving subsequent format requests from already-cached representations when available. > Sources: [src/request.ts:69-69](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L69-L69), [src/request.ts:220-239](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L220-L239) ### Body Extraction Flow When a body accessor like `.text()`, `.json()`, or `.parseBody()` is invoked, `#cachedBody` checks if the requested format already exists in `bodyCache`. If another body type was previously extracted and cached, Hono serializes or transforms the existing cached value using an interim `Response` object to satisfy the new format request without reading the underlying stream twice. ```typescript #cachedBody = (key: keyof Body) => { const { bodyCache, raw } = this const cachedBody = bodyCache[key] if (cachedBody) { return cachedBody } const anyCachedKey = Object.keys(bodyCache)[0] if (anyCachedKey) { return (bodyCache[anyCachedKey as keyof Body] as Promise).then((body) => { if (anyCachedKey === 'json') { body = JSON.stringify(body) } return new Response(body)[key]() }) } return (bodyCache[key] = raw[key]()) } ``` Sources: [src/request.ts:220-239](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L220-L239) > [!WARNING] > If `json` was previously cached, it must be explicitly serialized via `JSON.stringify()` before being passed into a new `Response` instance to prevent parsing errors during secondary format extractions. > Sources: [src/request.ts:231-233](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L231-L233) ### Supported Body Methods Hono exposes direct methods for parsing incoming payloads based on content type expectations, delegating form data parsing to helper utilities and JSON parsing to text extraction followed by `JSON.parse`. | Method | Return Type | Underlying Mechanism | | :--- | :--- | :--- | | `json()` | `Promise` | Retrieves cached text via `#cachedBody('text')` and parses it with `JSON.parse`. | | `text()` | `Promise` | Invokes `#cachedBody('text')` to consume the raw stream as a string. | | `parseBody()` | `Promise` | Delegates to the `parseBody` utility function supporting `multipart/form-data` and `application/x-www-form-urlencoded`. | ```typescript json(): Promise { return this.#cachedBody('text').then((text: string) => JSON.parse(text)) } text(): Promise { return this.#cachedBody('text') } async parseBody(options?: Partial) { return parseBody(this, options) } ``` Sources: [src/request.ts:212-218](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L212-L218), [src/request.ts:253-271](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L253-L271) ## Parameter and Query Extraction ### Route Parameter Resolution The `HonoRequest` class provides the `.param()` method to extract dynamic path parameters captured during route matching. Depending on whether a specific key is passed, `.param()` retrieves either a single decoded parameter via `#getDecodedParam()` or an entire dictionary of decoded route parameters via `#getAllDecodedParams()`. ```typescript param = ParamKeys

>( key: string extends P ? never : P2 extends `${infer _}?` ? never : P2 ): string param> = RemoveQuestion>>( key: P2 ): string | undefined param(key: string): string | undefined param(): Simplify>>> param(key?: string): unknown { return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams() } ``` Sources: [src/request.ts:94-104](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L94-L104) > [!NOTE] > Parameter values are extracted by mapping route table indices from the internal `#matchResult` tuple. If a parameter string contains percent-encoding (`%`), Hono automatically attempts URI component decoding using `tryDecodeURIComponent`. > Sources: [src/request.ts:106-124](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L106-L124) ### Decoding and Lookup Mechanics Internal parameter extraction relies on helper routines that inspect the match result array structure and resolve parameter keys against matched path segments. ```typescript #getDecodedParam(key: string): string | undefined { const paramKey = this.#matchResult[0][this.routeIndex][1][key] const param = this.#getParamValue(paramKey) return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param } #getAllDecodedParams(): Record { const decoded: Record = {} const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]) for (const key of keys) { const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]) if (value !== undefined) { decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value } } return decoded } #getParamValue(paramKey: any): string | undefined { return this.#matchResult[1] ? this.#matchResult[1][paramKey as any] : paramKey } ``` Sources: [src/request.ts:106-128](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L106-L128) ### Query String Extraction Helpers Query string parsing is handled by the `.query()` and `.queries()` methods, which delegate directly to URL utility functions `getQueryParam` and `getQueryParams` applied against the request URL. | Method | Overload Signatures | Underlying Utility | Purpose | | :--- | :--- | :--- | :--- | | `query()` | `query(key: string): string \| undefined` `query(): Record` | `getQueryParam(this.url, key)` | Retrieves a single query parameter value or a dictionary of all single-value query parameters. | | `queries()` | `queries(key: string): string[] \| undefined` `queries(): Record` | `getQueryParams(this.url, key)` | Retrieves all query parameter values as string arrays or a dictionary mapping keys to string arrays. | ```typescript query(key: string): string | undefined query(): Record query(key?: string) { return getQueryParam(this.url, key) } queries(key: string): string[] | undefined queries(): Record queries(key?: string) { return getQueryParams(this.url, key) } ``` Sources: [src/request.ts:148-171](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L148-L171) ## Serverless Event Adapters ### AWS Lambda and Lambda@Edge Conversion The AWS Lambda adapter translates API Gateway payloads (`APIGatewayProxyEvent` and `APIGatewayProxyEventV2`) and `Lambda@Edge` records into standard Fetch `Request` objects before dispatching them to the Hono application. The abstract `EventProcessor` class and its concrete implementations (`EventV1Processor` and `EventV2Processor`) extract routing properties, query strings, headers, and cookies to construct the unified request. For `Lambda@Edge`, `createRequest()` parses CloudFront event structures, resolves host headers from distribution domain names, and decodes base64-encoded request bodies via `decodeBase64`. ```typescript export class EventV2Processor extends EventProcessor { protected getPath(event: APIGatewayProxyEventV2): string { return event.rawPath } protected getMethod(event: APIGatewayProxyEventV2): string { return event.requestContext.http.method } protected getQueryString(event: APIGatewayProxyEventV2): string { return event.rawQueryString } ... ``` Sources: [src/adapter/aws-lambda/handler.ts:404-415](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L404-L415), [src/adapter/lambda-edge/handler.ts:152-184](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L152-L184) > [!CAUTION] > When processing V1 API Gateway integration events, query parameters originating from `multiValueQueryStringParameters` or `queryStringParameters` are re-encoded explicitly using `encodeURIComponent` to preserve the original URL format and prevent downstream parsing discrepancies. > Sources: [src/adapter/aws-lambda/handler.ts:453-468](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L453-L468) ### Cloudflare Pages and Service Workers Cloudflare Pages integration uses an `handle` function that accepts an `EventContext` containing the incoming `request`, `env` bindings, and execution controls like `waitUntil` and `passThroughOnException`. The handler passes these directly into `app.fetch()`. Similarly, the Service Worker adapter wraps fetch events via `evt.respondWith()`, passing `evt` as the [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) and executing a fallback fetch to `opts.fetch` when a response yields a `404 Not Found` status. ```typescript export const handle = ( app: Hono ): PagesFunction => (eventContext) => { return app.fetch( eventContext.request, { ...eventContext.env, eventContext }, { waitUntil: eventContext.waitUntil, passThroughOnException: eventContext.passThroughOnException, props: {}, } ) } ``` Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46), [src/adapter/service-worker/handler.ts:18-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts#L18-L36) ### Lightweight Platform Handlers Platform adapters for Netlify and Vercel act as thin transparent wrappers, directly binding standard `Request` objects and runtime execution contexts into the Hono application's core `app.fetch()` pipeline without additional payload transformation layers. | Adapter Module | Target Platform | Argument Signature | Core Dispatch Mechanism | | :--- | :--- | :--- | :--- | | `src/adapter/netlify/handler.ts` | Netlify Functions | `(req: Request, context: any)` | `app.fetch(req, { context })` | | `src/adapter/vercel/handler.ts` | Vercel Serverless | `(req: Request)` | `app.fetch(req)` | ```typescript export const handle = ( app: Hono ): ((req: Request, context: any) => Response | Promise) => { return (req: Request, context: any) => { return app.fetch(req, { context }) } } ``` Sources: [src/adapter/netlify/handler.ts:4-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L9), [src/adapter/vercel/handler.ts:4-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts#L4-L7) ## HTTP Exception Processing ### HTTPException Class Semantics The `HTTPException` class extends the native `Error` constructor to handle application-level faults such as authentication failures or invalid input. It accepts a `ContentfulStatusCode` status code which defaults to `500`, along with an optional `HTTPExceptionOptions` object containing custom properties. ```typescript export class HTTPException extends Error { readonly res?: Response readonly status: ContentfulStatusCode constructor(status: ContentfulStatusCode = 500, options?: HTTPExceptionOptions) { super(options?.message, { cause: options?.cause }) this.res = options?.res this.status = status } ... ``` Sources: [src/http-exception.ts:46-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L46-L59) > [!NOTE] > `HTTPException` supports an optional `cause` property passed directly to the underlying `Error` constructor, allowing error cause chaining during exception propagation. > Sources: [src/http-exception.ts:14-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L14-L18), [src/http-exception.ts:55-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L55-L56) ### Response Generation and Propagation The `getResponse()` method translates the exception into a standard Fetch `Response` object. If an explicit `res` response object was supplied in the constructor options, a new `Response` is instantiated using its body and headers combined with the exception's `status`. Otherwise, it falls back to creating a plain text response containing the error message and the status code. ```typescript getResponse(): Response { if (this.res) { const newResponse = new Response(this.res.body, { status: this.status, headers: this.res.headers, }) return newResponse } return new Response(this.message, { status: this.status, }) } } ``` Sources: [src/http-exception.ts:66-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/http-exception.ts#L66-L77) ## Upstream Request Forwarding ### Proxy Initialization and Request Building The `proxy` helper wraps standard Fetch API dispatches to forward incoming client requests to upstream origin servers. It accepts an input target and optional `ProxyRequestInit` configuration options, supporting custom fetch handlers and strict RFC compliance processing. Sources: [src/helper/proxy/index.ts:46-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L46-L48), [src/helper/proxy/index.ts:160-166](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L160-L166) The `buildRequestInitFromRequest` helper clones incoming request properties, initializing the `duplex` property to `'half'` when a request body is present. It filters out hop-by-hop headers defined in the specification and evaluates strict RFC compliance when requested. Sources: [src/helper/proxy/index.ts:50-91](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L50-L91) | Hop-by-Hop Header | Action | | :--- | :--- | | `connection` | Deleted or parsed per `strictConnectionProcessing` | | `keep-alive` | Deleted | | `proxy-authenticate` | Deleted | | `proxy-authorization` | Deleted | | `te` | Deleted | | `trailer` | Deleted | | `transfer-encoding` | Deleted | | `upgrade` | Deleted | Sources: [src/helper/proxy/index.ts:10-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L10-L19), [src/helper/proxy/index.ts:80-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L80-L82) > [!WARNING] > By default, `strictConnectionProcessing` is set to `false`, causing the `Connection` header to be ignored to prevent potential Hop-by-Hop Header Injection attacks from untrusted clients. > Sources: [src/helper/proxy/index.ts:35-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L35-L36), [src/helper/proxy/index.ts:164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L164) ### Header Preprocessing and Validation When `strictConnectionProcessing` is enabled, the helper splits the `connection` header value by commas and validates each entry against `ALLOWED_TOKEN_PATTERN` to ensure proper token syntax. If an invalid header name is encountered, an `HTTPException` with status `400` is thrown. Sources: [src/helper/proxy/index.ts:21-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L21-L22), [src/helper/proxy/index.ts:60-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L60-L77) ```typescript const ALLOWED_TOKEN_PATTERN = /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/ ``` Sources: [src/helper/proxy/index.ts:21-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L21-L22) > [!CAUTION] > Enabling `strictConnectionProcessing` parses and removes listed headers per RFC 9110 Section 7.6.1 and should only be used in trusted internal environments. > Sources: [src/helper/proxy/index.ts:37-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L37-L41), [src/helper/proxy/index.ts:60-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L60-L77) The `preprocessRequestInit` function normalizes custom header initializers supplied as plain objects into standard `Headers` instances, deleting entries where the value evaluates to `null` or `undefined`. Sources: [src/helper/proxy/index.ts:93-113](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L93-L113) ### Dispatch and Response Sanitization After constructing the upstream request, the helper deletes the `accept-encoding` header and dispatches the request using either `customFetch` or the global `fetch` function. Sources: [src/helper/proxy/index.ts:168-174](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L168-L174) ```typescript const req = new Request(input, { ...buildRequestInitFromRequest(raw, strictConnectionProcessing), ...preprocessRequestInit(requestInit as RequestInit), }) req.headers.delete('accept-encoding') const res = await (customFetch || fetch)(req) ``` Sources: [src/helper/proxy/index.ts:168-174](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L168-L174) Response headers are sanitized by removing all hop-by-hop headers. If a `content-encoding` header is present on the upstream response, both `content-encoding` and `content-length` are deleted because the content length no longer matches the uncompressed payload size. Sources: [src/helper/proxy/index.ts:175-189](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts#L175-L189) ## Related - [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) - [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) - [Middleware Composition](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/middleware-composition) --- ## Technical docs: Execution Context URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context

Relevant source files The following files were used as context for generating this wiki page: - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/middleware/request-id/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts) - [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts) - [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts) - [src/middleware/timing/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/index.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/adapter/aws-lambda/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/types.ts) - [src/middleware/context-storage/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts) - [src/jsx/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [src/adapter/bun/server.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts) - [src/adapter/lambda-edge/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts) - [src/middleware/language/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/index.ts) - [src/middleware/secure-headers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/index.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/helper/testing/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/testing/index.ts) - [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts)
## Overview The `Context` class manages the complete execution lifecycle for incoming HTTP requests [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L361). It encapsulates routing parameters, request headers, environment bindings, and response generation utilities within a unified interface passed to handlers and middleware [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315-L434), [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L94-L198). Sources: [src/context.ts:293-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L361) Sources: [src/context.ts:315-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315-L434), [src/request.ts:94-198](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts#L94-L198) ## Context Lifecycle and Internal State ### Constructor Initialization and Request Wrapping The `Context` class constructor takes a raw Web Standard `Request` object and an optional `ContextOptions` record [src/context.ts:352-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L352-L361). It retains the underlying request as `#rawRequest` and initializes instance parameters such as execution contexts, environment bindings, not-found handlers, path specifications, and routing match results if provided [src/context.ts:300-360](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L300-L360). Sources: [src/context.ts:352-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L352-L361) Request parsing is deferred via the `.req` getter property, which lazily instantiates a `HonoRequest` wrapper around `#rawRequest`, `#path`, and `#matchResult` upon first access [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369). Similarly, Cloudflare Pages middleware integration constructs a `Context` instance by passing the event execution context alongside extended bindings [src/adapter/cloudflare-pages/handler.ts:60-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L60-L64). Sources: [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369) Sources: [src/adapter/cloudflare-pages/handler.ts:60-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L60-L64) ```typescript constructor(req: Request, options?: ContextOptions) { this.#rawRequest = req if (options) { this.#executionCtx = options.executionCtx this.env = options.env this.#notFoundHandler = options.notFoundHandler this.#path = options.path this.#matchResult = options.matchResult } } ``` Sources: [src/context.ts:352-361](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L352-L361) ```typescript return async (executionCtx) => { const context = new Context(executionCtx.request, { env: { ...executionCtx.env, eventContext: executionCtx }, executionCtx, }) ``` Sources: [src/adapter/cloudflare-pages/handler.ts:60-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L60-L64) ### Execution State and Response Tracking An active `Context` instance maintains internal tracking flags and response fields throughout the handler execution cycle [src/context.ts:315-345](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315-L345). The `finalized` boolean flag marks whether a response has been committed or set [src/context.ts:317](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L317). Platform-specific capabilities such as Cloudflare Workers event bindings are accessed through strict getters: the `event` getter verifies the presence of `respondWith` on the execution context, while the `executionCtx` getter validates standard platform contexts, throwing errors if accessed outside a supported environment [src/context.ts:377-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L377-L397). Sources: [src/context.ts:315-345](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315-L345) Sources: [src/context.ts:317](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L317) Sources: [src/context.ts:377-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L377-L397) ```typescript get res(): Response { return (this.#res ||= createResponseInstance(null, { headers: (this.#preparedHeaders ??= new Headers()), })) } /** * Sets the Response object for the current request. * * @param _res - The Response object to set. */ set res(_res: Response | undefined) { if (this.#res && _res) { _res = createResponseInstance(_res.body, _res) for (const [k, v] of this.#res.headers.entries()) { if (k === 'content-type') { continue } if (k === 'set-cookie') { const cookies = this.#res.headers.getSetCookie() _res.headers.delete('set-cookie') for (const cookie of cookies) { _res.headers.append('set-cookie', cookie) } } else { _res.headers.set(k, v) } } } this.#res = _res this.finalized = true } ``` Sources: [src/context.ts:403-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L403-L434) > [!NOTE] > Setting the response property (`c.res = ...`) automatically marks the context as finalized and copies existing header entries—such as preserving set-cookie arrays and skipping duplicate content types—into the incoming response instance [src/context.ts:414-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L414-L434). Sources: [src/context.ts:414-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L414-L434) The table below details the internal state properties managed directly within the `Context` class instance. | Field / Property | Internal Variable | Type | Description | | :--- | :--- | :--- | :--- | | `req` | `#req`, `#rawRequest` | `HonoRequest \| undefined`, `Request` | Lazily wrapped request accessor and underlying fetch request [src/context.ts:300-301, 366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L300-L301) | | `env` | `env` | `E['Bindings']` | Environment variables, secrets, and bindings object [src/context.ts:315](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L315) | | `error` | `error` | `Error \| undefined` | Captured error object thrown during middleware or handler execution [src/context.ts:333](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L333) | | `event` | `#executionCtx` | `FetchEventLike` | FetchEvent instance supporting `respondWith` [src/context.ts:336, 377-383](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L336) | | `executionCtx` | `#executionCtx` | `ExecutionContext` | Platform execution context supporting methods like `waitUntil` [src/context.ts:336, 391-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L336) | | `res` | `#res`, `#preparedHeaders` | `Response`, `Headers \| undefined` | Current response object and prepared headers buffer [src/context.ts:337, 341, 403-407](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L337) | | `finalized` | `finalized` | `boolean` | Flag indicating whether the response has been sent or locked [src/context.ts:317](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L317) | Sources: [src/context.ts:300-434](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L300-L434) ## Request Parameter and Header Accessors ### HonoRequest Initialization and Parameter Retrieval The `Context` instance exposes incoming request properties through its `.req` property [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369). Accessing `c.req` triggers the lazy instantiation of a `HonoRequest` wrapper, combining the raw underlying `Request` object with route path variables and match results [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369). Sources: [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369) ```typescript get req(): HonoRequest { this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult) return this.#req } ``` Sources: [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369) > [!NOTE] > The `HonoRequest` instance is initialized precisely on first access (`this.#req ??= ...`), avoiding parsing overhead for requests that do not inspect parameters, headers, or query strings [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369). Sources: [src/context.ts:366-369](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L366-L369) ## Variable Storage and Context Typing ### Context Variable Map and Generic Constraints The `Context` class manages scoped variables across middleware and request handlers via a private `#var` instance of JavaScript's `Map` [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316). These variables are typed through the generic `E` constraint parameter extending `Env`, allowing applications to define strict typing for key-value pairs shared during request execution [src/context.ts:293-295](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L295). Sources: [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316) Sources: [src/context.ts:293-295](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L293-L295) ```typescript #var: Map | undefined ``` Sources: [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316) > [!NOTE] > The internal `#var` map is lazily initialized on first write or read operation, preventing unnecessary allocation for request contexts that do not utilize scoped variables [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316). Sources: [src/context.ts:316](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L316) ## Response Construction and Helpers ### Response Instance Creation and Default Types Response generation relies on underlying Web Standard constructor wrappers [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291). The helper `createResponseInstance` wraps `new Response(body, init)`, providing the foundation for text, stream, and binary outputs [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291). Additionally, `TEXT_PLAIN` defines the default UTF-8 plain text content type string [src/context.ts:279](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L279), while `setDefaultContentType` merges content type headers with existing header records [src/context.ts:281-286](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L281-L286). Sources: [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291) Sources: [src/context.ts:279](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L279), [src/context.ts:281-286](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L281-L286) ```typescript export const TEXT_PLAIN = 'text/plain; charset=UTF-8' const setDefaultContentType = (contentType: string, headers?: HeaderRecord): HeaderRecord => { return { 'Content-Type': contentType, ...headers, } } const createResponseInstance = ( body?: BodyInit | null | undefined, init?: globalThis.ResponseInit ): Response => new Response(body, init) ``` Sources: [src/context.ts:279-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L279-L291) > [!WARNING] > Modifying headers after a response has been finalized forces Hono to instantiate a new underlying `Response` object to prevent mutation errors on immutable response streams [src/context.ts:516-518](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L516-L518). Sources: [src/context.ts:516-518](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L516-L518) ### Stream SSE Execution Walkthrough The `streamSSE` helper orchestrates Server-Sent Events by initializing a transform stream, invoking `c.header` to configure transport headers, and utilizing `createResponseInstance` to generate the final response [src/helper/streaming/sse.ts:72-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L72-L100), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291). Sources: [src/helper/streaming/sse.ts:72-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L72-L100), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291) 1. `streamSSE` initializes a `TransformStream` and wraps it in an `SSEStreamingApi` instance [src/helper/streaming/sse.ts:77-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L77-L78). 2. `isOldBunVersion()` checks for legacy runtime behavior, binding an abort listener to `c.req.raw.signal` if necessary [src/helper/streaming/sse.ts:80-87](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L80-L87). 3. `contextStash.set` caches the context against the response readable stream to prevent premature garbage collection in Bun [src/helper/streaming/sse.ts:89-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L89-L90). 4. `c.header` sets required transport and protocol headers including `Transfer-Encoding`, `Content-Type`, `Cache-Control`, and `Connection` [src/helper/streaming/sse.ts:92-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L92-L95), [src/context.ts:515-527](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L515-L527). 5. `run` executes the user callback with error handling and automatic stream closure [src/helper/streaming/sse.ts:47-68](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L47-L68), [97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L97). 6. `createResponseInstance` is invoked through response helpers to construct the final Response wrapping `stream.responseReadable` [src/helper/streaming/sse.ts:99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L99), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291). Sources: [src/helper/streaming/sse.ts:77-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L77-L78) Sources: [src/helper/streaming/sse.ts:80-87](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L80-L87) Sources: [src/helper/streaming/sse.ts:89-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L89-L90) Sources: [src/helper/streaming/sse.ts:92-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L92-L95), [src/context.ts:515-527](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L515-L527) Sources: [src/helper/streaming/sse.ts:47-68](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L47-L68), [src/helper/streaming/sse.ts:97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L97) Sources: [src/helper/streaming/sse.ts:99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L99), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291) ```typescript export const streamSSE = ( c: Context, cb: (stream: SSEStreamingApi) => Promise, onError?: (e: Error, stream: SSEStreamingApi) => Promise ): Response => { const { readable, writable } = new TransformStream() const stream = new SSEStreamingApi(writable, readable) // Until Bun v1.1.27, Bun didn't call cancel() on the ReadableStream for Response objects from Bun.serve() if (isOldBunVersion()) { c.req.raw.signal.addEventListener('abort', () => { if (!stream.closed) { stream.abort() } }) } // in bun, `c` is destroyed when the request is returned, so hold it until the end of streaming contextStash.set(stream.responseReadable, c) c.header('Transfer-Encoding', 'chunked') c.header('Content-Type', 'text/event-stream') c.header('Cache-Control', 'no-cache') c.header('Connection', 'keep-alive') run(stream, cb, onError) return c.newResponse(stream.responseReadable) } ``` Sources: [src/helper/streaming/sse.ts:72-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L72-L100) ```mermaid sequenceDiagram participant streamSSE as streamSSE (sse.ts) participant Context as Context (context.ts) participant header as header (context.ts) participant createResponseInstance as createResponseInstance (context.ts) streamSSE->>Context: c.header('Transfer-Encoding', 'chunked') Context->>header: header(name, value, options) streamSSE->>Context: c.newResponse(stream.responseReadable) Context->>createResponseInstance: createResponseInstance(body, init) ``` Sources: [src/helper/streaming/sse.ts:72-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L72-L100), [src/context.ts:288-291](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L288-L291) > [!NOTE] An internal `contextStash` WeakMap holds a reference to the active `Context` keyed by `stream.responseReadable`, ensuring the request context remains accessible throughout long-lived streaming connections [src/helper/streaming/sse.ts:70-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L70-L90). Sources: [src/helper/streaming/sse.ts:70-90](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts#L70-L90) ## Adapter Bindings and Environment Access ### Runtime Identification and Environment Resolution Hono resolves environment bindings and execution contexts across heterogeneous JavaScript runtimes by combining runtime detection helpers with platform-specific adapter handlers. The `getRuntimeKey()` utility inspects `globalThis` properties and user agent strings to classify the active platform into one of the supported runtime identifiers [src/helper/adapter/index.ts:50-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L50-L84). Once identified, the `env()` helper dynamically dispatches to the correct environment provider, returning process environment variables or platform-native binding stores [src/helper/adapter/index.ts:10-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L10-L41). Sources: [src/helper/adapter/index.ts:50-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L50-L84) Sources: [src/helper/adapter/index.ts:10-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L10-L41) | Runtime Key | Detection Mechanism | Environment Source | | :--- | :--- | :--- | | `bun` | `navigator.userAgent` starts with `Bun` | `process.env` | | `node` | `navigator.userAgent` starts with `Node.js` or `process.release.name === 'node'` | `process.env` | | `deno` | `navigator.userAgent` starts with `Deno` | `Deno.env.toObject()` | | `workerd` | `navigator.userAgent` starts with `Cloudflare-Workers` | `c.env` | | `edge-light` | `globalThis.EdgeRuntime` is a string | `process.env` | | `fastly` | `globalThis.fastly !== undefined` | `{}` | | `other` | Fallback when no platform signature matches | `{}` | Sources: [src/helper/adapter/index.ts:8-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L8-L48) ```typescript export type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'other' export const env = < T extends Record, C extends Context = Context<{ Bindings: T }>, >( c: T extends Record ? Context : C, runtime?: Runtime ): T & C['env'] => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const global = globalThis as any const globalEnv = global?.process?.env as T runtime ??= getRuntimeKey() const runtimeEnvHandlers: Record T> = { bun: () => globalEnv, node: () => globalEnv, 'edge-light': () => globalEnv, deno: () => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore return Deno.env.toObject() as T }, workerd: () => c.env, // On Fastly Compute, you can use the ConfigStore to manage user-defined data. fastly: () => ({}) as T, other: () => ({}) as T, } return runtimeEnvHandlers[runtime]() } export const knownUserAgents: Partial> = { deno: 'Deno', bun: 'Bun', workerd: 'Cloudflare-Workers', node: 'Node.js', } ``` Sources: [src/helper/adapter/index.ts:8-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L8-L48) > [!NOTE] > The `env()` helper requires an explicit runtime parameter or falls back to `getRuntimeKey()`, which inspects `navigator.userAgent` before checking runtime-specific global objects [src/helper/adapter/index.ts:17-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L17-L23). Sources: [src/helper/adapter/index.ts:17-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L17-L23) ### Platform Adapter Handlers and Execution Contexts Cloudflare Pages, AWS Lambda, and Netlify integrate with Hono by mapping native platform events and execution contexts into the standard `app.fetch()` signature [src/adapter/aws-lambda/handler.ts:268-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L268-L272), [src/adapter/cloudflare-pages/handler.ts:37-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L37-L45), [src/adapter/netlify/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L8). Cloudflare Pages passes `eventContext.request`, environment bindings augmented with `eventContext`, and an execution options object containing `waitUntil` and `passThroughOnException` callbacks [src/adapter/cloudflare-pages/handler.ts:37-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L37-L45). Sources: [src/adapter/aws-lambda/handler.ts:268-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L268-L272), [src/adapter/cloudflare-pages/handler.ts:37-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L37-L45), [src/adapter/netlify/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L8) Sources: [src/adapter/cloudflare-pages/handler.ts:37-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L37-L45) ```typescript export const handle = ( app: Hono ): PagesFunction => (eventContext) => { return app.fetch( eventContext.request, { ...eventContext.env, eventContext }, { waitUntil: eventContext.waitUntil, passThroughOnException: eventContext.passThroughOnException, props: {}, } ) } ``` Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46) AWS Lambda adapters process incoming API Gateway or ALB events via event processors (`EventV1Processor` and `EventV2Processor`), converting event payloads into standard `Request` instances and passing the raw `event`, `requestContext`, and `lambdaContext` through to `app.fetch()` [src/adapter/aws-lambda/handler.ts:252-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L252-L272). Similarly, Netlify's adapter delegates incoming requests directly to `app.fetch()` accompanied by the Netlify execution context object [src/adapter/netlify/handler.ts:4-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L10). Connection info helpers, such as the Lambda@Edge implementation, extract client IP addresses directly from nested event records stored within `c.env` [src/adapter/lambda-edge/conninfo.ts:11-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts#L11-L14). Sources: [src/adapter/aws-lambda/handler.ts:252-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L252-L272) Sources: [src/adapter/netlify/handler.ts:4-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L10) Sources: [src/adapter/lambda-edge/conninfo.ts:11-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts#L11-L14) ```typescript return async (event, lambdaContext?) => { const processor = getProcessor(event) let req, requestContext try { req = processor.createRequest(event) requestContext = getRequestContext(event) } catch (error) { console.error('Error processing request:', error) const errorResponse = error instanceof TypeError ? new Response('Invalid request', { status: 400 }) : new Response('Internal Server Error', { status: 500 }) return processor.createResult(event, errorResponse, { isContentTypeBinary }) } const res = await app.fetch(req, { event, requestContext, lambdaContext, }) return processor.createResult(event, res, { isContentTypeBinary }) } } ``` Sources: [src/adapter/aws-lambda/handler.ts:252-276](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L252-L276) > [!WARNING] > Accessing `c.event` or `c.executionCtx` on platforms that do not supply a matching execution context object will throw an explicit error (`This context has no FetchEvent` or `This context has no ExecutionContext`) [src/context.ts:377-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L377-L397). Sources: [src/context.ts:377-397](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts#L377-L397) ## Related - [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle) - [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) - [Context Storage](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/context-storage) --- ## Technical docs: Middleware Composition URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/middleware-composition
Relevant source files The following files were used as context for generating this wiki page: - [src/compose.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts) - [src/middleware/combine/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts) - [src/helper/factory/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/validator/validator.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/validator/validator.ts) - [src/utils/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts)
## Overview Middleware composition in Hono orchestrates request processing pipelines through recursive dispatching and onion-model execution [src/compose.ts:15-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L72). By combining middleware functions, conditional routing helpers, and type-safe factories, Hono enables modular request interception, error handling, and terminal route delegation [src/compose.ts:15-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L72), [src/middleware/combine/index.ts:38-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L164), [src/helper/factory/index.ts:353-360](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L353-L360). Sources: [src/compose.ts:15-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L72), [src/middleware/combine/index.ts:38-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L164), [src/helper/factory/index.ts:353-360](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L353-L360), [src/types.ts:305-347](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts#L305-L347), [src/utils/handler.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8-L14) ## Onion Model Execution with Compose ### Recursive Dispatch Loop Mechanics The `compose` function structures middleware execution using an internal asynchronous `dispatch(i)` loop derived from the `koa-compose` package [src/compose.ts:5-32](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L5-L32). It accepts a `middleware` array of nested tuples, an optional `onError` handler, and an optional `onNotFound` handler, returning a function that executes the pipeline against an [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) instance [src/compose.ts:15-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L19). ```typescript export const compose = ( middleware: [[Function, unknown], unknown][] | [[Function]][], onError?: ErrorHandler, onNotFound?: NotFoundHandler ): ((context: Context, next?: Next) => Promise) => { return (context, next) => { let index = -1 return dispatch(0) ``` Sources: [src/compose.ts:15-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L24) Each invocation tracks index advancement through the `index` local variable [src/compose.ts:21-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L21-L36). If `dispatch(i)` is invoked with an index less than or equal to the current `index` marker, it immediately throws an error [src/compose.ts:33-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L33-L35). This guard prevents middleware from calling `next()` multiple times within the same execution cycle [src/compose.ts:33-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L33-L35). > [!WARNING] > Calling `next()` more than once within a single middleware layer triggers an immediate `Error` with the message `'next() called multiple times'` due to the `i <= index` check in the `dispatch` loop. Sources: [src/compose.ts:33-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L33-L35) ### Pipeline Resolution and Handler Invocation When a middleware item exists at the current index `i`, `dispatch` extracts the handler function from `middleware[i][0][0]` and updates `context.req.routeIndex` to match the current execution index [src/compose.ts:42-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L42-L44). When `i` reaches the end of the middleware array (`i === middleware.length`), the dispatcher checks for an outer `next` function [src/compose.ts:45-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L45-L47). ```typescript if (middleware[i]) { handler = middleware[i][0][0] context.req.routeIndex = i } else { handler = (i === middleware.length && next) || undefined } ``` Sources: [src/compose.ts:42-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L42-L48) If a `handler` is resolved, it is executed within a `try...catch` block, passing `context` and a continuation callback `() => dispatch(i + 1)` [src/compose.ts:49-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L49-L51). If an error is thrown during handler execution and an `onError` function is provided, `context.error` is assigned the error, `onError` is invoked, and `isError` is set to `true` [src/compose.ts:52-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L52-L56). If no `onError` handler is present, the error is rethrown [src/compose.ts:57-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L57-L59). ```typescript if (handler) { try { res = await handler(context, () => dispatch(i + 1)) } catch (err) { if (err instanceof Error && onError) { context.error = err res = await onError(err, context) isError = true } else { throw err } } } else { if (context.finalized === false && onNotFound) { res = await onNotFound(context) } } ``` Sources: [src/compose.ts:49-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L49-L65) When no handler is found and the response has not been finalized (`context.finalized === false`), an optional `onNotFound` handler is executed [src/compose.ts:61-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L61-L64). Finally, if a response `res` is returned and either the response is unfinalized or an error occurred, `context.res` is updated with `res`, and the `context` is returned [src/compose.ts:67-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L67-L70). Sources: [src/compose.ts:67-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L67-L70) ## Conditional Routing with Combine Middleware ### Conditional Composition Helpers The combine middleware module provides advanced flow-control helpers (`some`, `every`, and `except`) that evaluate middleware arrays based on boolean condition functions or path pattern strings [src/middleware/combine/index.ts:38-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L165). These functions inspect the Execution Context or intercept continuation calls to conditionally bypass or enforce middleware execution [src/middleware/combine/index.ts:38-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L165). ```typescript export const some = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => { return async function some(c, next) { let isNextCalled = false const wrappedNext = () => { isNextCalled = true return next() } let lastError: unknown for (const handler of middleware) { try { const result = await handler(c, wrappedNext) if (result === true && !c.finalized) { await wrappedNext() } else if (result === false) { lastError = new Error('No successful middleware found') continue } lastError = undefined break } catch (error) { lastError = error if (isNextCalled) { break } } } if (lastError) { throw lastError } } } ``` Sources: [src/middleware/combine/index.ts:38-69](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L69) The `some` helper iterates over an array of middleware or condition functions sequentially [src/middleware/combine/index.ts:38-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L47). If a handler returns `true` and the context is not finalized, it invokes `wrappedNext()` to proceed, halting subsequent evaluation upon the first successful or non-error exit [src/middleware/combine/index.ts:47-57](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L47-L57). If a handler returns `false`, it records a new `Error('No successful middleware found')` and continues [src/middleware/combine/index.ts:52-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L52-L55). ```typescript export const every = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => { return async function every(c, next) { const currentRouteIndex = c.req.routeIndex await compose( middleware.map((m) => [ [ async (c: Context, next: Next) => { c.req.routeIndex = currentRouteIndex // should be unchanged in this context const res = await m(c, next) if (res === false) { throw new Error('Unmet condition') } return res }, ], ]) )(c, next) } } ``` Sources: [src/middleware/combine/index.ts:99-117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L99-L117) The `every` helper wraps all provided middleware items inside a `compose` pipeline [src/middleware/combine/index.ts:99-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L99-L115). It preserves `c.req.routeIndex` across individual wrapped executions and throws an `Error('Unmet condition')` if any inner handler returns `false` [src/middleware/combine/index.ts:101-111](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L101-L111). > [!NOTE] > The `every` helper explicitly resets `c.req.routeIndex` to the parent route index inside each wrapped handler to ensure consistent route index tracking during composite pipeline execution. Sources: [src/middleware/combine/index.ts:101-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L101-L106) ### Path Pattern Matching and Execution Walkthrough The `except` helper accepts condition specifiers that can be strings, condition functions, or arrays of both [src/middleware/combine/index.ts:141-146](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L141-L146). String patterns are added to a private `TrieRouter` instance using `METHOD_NAME_ALL`, while condition functions are collected directly into an evaluation array [src/middleware/combine/index.ts:145-155](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L145-L155). If a router was initialized, an additional condition is prepended that checks if `router.match(METHOD_NAME_ALL, c.req.path)` successfully resolves [src/middleware/combine/index.ts:149-159](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L157-L159). ```typescript export const except = ( condition: string | Condition | (string | Condition)[], ...middleware: MiddlewareHandler[] ): MiddlewareHandler => { let router: TrieRouter | undefined = undefined const conditions = (Array.isArray(condition) ? condition : [condition]) .map((condition) => { if (typeof condition === 'string') { router ||= new TrieRouter() router.add(METHOD_NAME_ALL, condition, true) } else { return condition } }) .filter(Boolean) as Condition[] if (router) { conditions.unshift((c: Context) => !!router?.match(METHOD_NAME_ALL, c.req.path)?.[0]?.[0]?.[0]) } const handler = some((c: Context) => conditions.some((cond) => cond(c)), every(...middleware)) return async function except(c, next) { await handler(c, next) } } ``` Sources: [src/middleware/combine/index.ts:141-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L141-L165) When an incoming request reaches an `except` middleware combination, execution flows through a precise sequence of internal helper calls before dispatching [src/middleware/combine/index.ts:161-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L161-L164). 1. `except` evaluates path conditions and constructs a composite handler via `some` and `every` [src/middleware/combine/index.ts:161-162](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L161-L162). 2. `handler` executes the `some` wrapper logic to test whether the exclusion condition matches the context [src/middleware/combine/index.ts:39-68](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L39-L68). 3. `every` maps the remaining middleware array into individual wrapped handlers that enforce boolean checks [src/middleware/combine/index.ts:102-114](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L102-L114). 4. `compose` aggregates the mapped middleware items into a linear execution array [src/compose.ts:15-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L19). 5. `dispatch` recursively steps through index `i` to execute each middleware layer in the onion pipeline [src/compose.ts:32-71](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L32-L71). ```mermaid sequenceDiagram participant Except as src/middleware/combine/index.ts (except) participant Handler as src/middleware/combine/index.ts (some) participant Every as src/middleware/combine/index.ts (every) participant Compose as src/compose.ts (compose) participant Dispatch as src/compose.ts (dispatch) Except->>Handler: constructs conditional handler via some Handler->>Every: executes alternate branch via every Every->>Compose: wraps middleware array with compose Compose->>Dispatch: initiates recursive dispatch(0) loop ``` Sources: [src/compose.ts:15-71](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/compose.ts#L15-L71), [src/middleware/combine/index.ts:39-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L39-L164) ## Short-Circuiting and Wrapped Execution ### Evaluation Tracing and Control Flow When composite middleware runs, execution bypasses subsequent handlers or short-circuits depending on return values and exception states. The `some` implementation manages this flow by maintaining an `isNextCalled` flag and a `wrappedNext` closure that delegates directly to the underlying `next()` function [src/middleware/combine/index.ts:38-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L44). ```typescript export const some = (...middleware: (MiddlewareHandler | Condition)[]): MiddlewareHandler => { return async function some(c, next) { let isNextCalled = false const wrappedNext = () => { isNextCalled = true return next() } let lastError: unknown for (const handler of middleware) { try { const result = await handler(c, wrappedNext) if (result === true && !c.finalized) { await wrappedNext() } else if (result === false) { lastError = new Error('No successful middleware found') continue } lastError = undefined break } catch (error) { lastError = error if (isNextCalled) { break } } } if (lastError) { throw lastError } } } ``` Sources: [src/middleware/combine/index.ts:38-69](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L69) Incoming requests flow through a specific sequence of internal functions during short-circuiting operations [src/middleware/combine/index.ts:38-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L164). 1. `except` evaluates route path patterns and custom predicates [src/middleware/combine/index.ts:141-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L141-L164). 2. `handler` invokes the composed `some` wrapper [src/middleware/combine/index.ts:161-163](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L161-L163). 3. `some` iterates over its middleware arguments, calling each with `c` and `wrappedNext` [src/middleware/combine/index.ts:47-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L47-L49). 4. `wrappedNext` sets `isPreserved` flags or `isNextCalled` to `true` before triggering downstream execution [src/middleware/combine/index.ts:41-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L41-L44). ```mermaid sequenceDiagram participant Except as src/middleware/combine/index.ts (except) participant Handler as src/middleware/combine/index.ts (handler) participant Some as src/middleware/combine/index.ts (some) participant WrappedNext as src/middleware/combine/index.ts (wrappedNext) Except->>Handler: invokes wrapped composite handler Handler->>Some: evaluates condition set in some Some->>WrappedNext: triggers wrappedNext on match WrappedNext->>WrappedNext: marks isNextCalled = true and invokes next() ``` Sources: [src/middleware/combine/index.ts:38-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L38-L164) > [!WARNING] > If a handler inside `some` invokes `wrappedNext()` and subsequently throws an error, the catch block checks `isNextCalled`; if true, iteration breaks immediately to prevent duplicate error handling or redundant execution [src/middleware/combine/index.ts:58-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L58-L63). Sources: [src/middleware/combine/index.ts:58-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/combine/index.ts#L58-L63) ## Middleware Type Safety and Factory Helpers ### Factory Initialization and Middleware Typing The `Factory` class and `createFactory` helper manage environment bindings (`Env`), route path types (`P`), and default application options when instantiating `Hono` apps [src/helper/factory/index.ts:332-366](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L332-L366). ```typescript export class Factory { private initApp?: InitApp #defaultAppOptions?: HonoOptions constructor(init?: { initApp?: InitApp; defaultAppOptions?: HonoOptions }) { this.initApp = init?.initApp this.#defaultAppOptions = init?.defaultAppOptions } createApp = (options?: HonoOptions): Hono => { const app = new Hono( options && this.#defaultAppOptions ? { ...this.#defaultAppOptions, ...options } : (options ?? this.#defaultAppOptions) ) if (this.initApp) { this.initApp(app) } return app } ``` Sources: [src/helper/factory/index.ts:332-351](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L332-L351) > [!NOTE] > The `Factory` constructor accepts an object with `initApp` and `defaultAppOptions`, which are merged during `createApp` execution to unify global middleware and configuration [src/helper/factory/index.ts:336-351](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L336-L351). Sources: [src/helper/factory/index.ts:336-351](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L336-L351) ### Chained Handler Intersections Chaining multiple handlers via factory definitions requires intersecting non-any environment types (`Env`) and input constraints (`Input`) across up to ten sequential parameters [src/helper/factory/index.ts:77-329](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L77-L329). Type parameters use `IntersectNonAnyTypes` to accumulate context extensions without polluting the base types [src/helper/factory/index.ts:88-92](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L88-L92). | Generic Parameter | Base Type / Constraint | Purpose | | :--- | :--- | :--- | | `E` / `E2`–`E11` | `Env` | Environment binding accumulation across chained handlers | | `I` / `I2`–`I10` | `Input` | Request input validation types and schema intersections | | `R` / `R2`–`R10` | `HandlerResponse` | Return type validation for individual middleware steps | | `P` | `string` | URL parameter matching string constraint | Sources: [src/helper/factory/index.ts:77-329](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/factory/index.ts#L77-L329) ## Handler Reflection and Middleware Inspection ### Introspecting Function Signatures and Target Handlers Hono provides utility functions to inspect handler chains, distinguishing middleware from terminal route handlers by examining function argument lengths and unwrapping composed wrappers [src/utils/handler.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8-L14). The `isMiddleware` helper checks whether a handler function expects multiple parameters, corresponding to the `(c, next)` middleware signature [src/utils/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8). The `findTargetHandler` utility recursively inspects composed handlers via the `COMPOSED_HANDLER` symbol to locate the underlying terminal or base handler [src/utils/handler.ts:9-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L9-L14). ```typescript export const isMiddleware = (handler: Function) => handler.length > 1 export const findTargetHandler = (handler: Function): Function => { // eslint-disable-next-line @typescript-eslint/no-explicit-any return (handler as any)[COMPOSED_HANDLER] ? // eslint-disable-next-line @typescript-eslint/no-explicit-any findTargetHandler((handler as any)[COMPOSED_HANDLER]) : handler ``` Sources: [src/utils/handler.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8-L14) > [!NOTE] > Because `isMiddleware` evaluates `handler.length > 1`, terminal handlers taking only the Context argument `(c)` return `false`, whereas middleware and wrapped handlers taking `(c, next)` return `true` [src/utils/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8). Sources: [src/utils/handler.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/handler.ts#L8) ## Related - [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) - [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) --- ## Technical docs: Presets and Builds URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds
Relevant source files The following files were used as context for generating this wiki page: - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts) - [src/middleware/compress/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts) - [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts) - [jsr.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [runtime-tests/deno-jsx/deno.precompile.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno-jsx/deno.precompile.json) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts) - [src/helper/ssg/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/index.ts) - [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [perf-measures/bundle-check/scripts/check-bundle-size.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts) - [src/middleware/pretty-json/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/pretty-json/index.ts) - [src/helper/css/common.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/css/common.ts) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts) - [src/adapter/netlify/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/index.ts) - [src/middleware/body-limit/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts) - [src/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [runtime-tests/deno/deno.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno/deno.json) - [src/helper/accepts/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/index.ts) - [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts)
## Overview The presets and builds system provides specialized distribution bundles, entry points, and routing optimizations tailored for different runtime performance characteristics and footprint constraints. Hono delivers standard functionality through its core router composition while offering lightweight distribution presets such as `[[Application Core]]` routing alternatives, package export mappings across `package.json` and `jsr.json`, and automated bundle size auditing harnesses [[src/preset/quick.ts:1-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L1-L23), [[package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [[src/preset/tiny.ts:1-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L1-L19), [[jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106), [perf-measures/bundle-check/scripts/check-bundle-size.ts:1-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L1-L50). Sources: [src/preset/quick.ts:1-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L1-L23), [package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [src/preset/tiny.ts:1-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L1-L19), [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106), [perf-measures/bundle-check/scripts/check-bundle-size.ts:1-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L1-L50) ## Preset Architecture and Entry Points ### Specialized Distribution Entry Points Hono exposes multiple public distribution entry points designed for different runtime environments, bundle size thresholds, and routing performance profiles. The standard entry point at `.` resolves to the main package distribution, while specialized preset modules such as `[[Application Core]]` routing bundles target restricted environments [package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106). Hono organizes its distribution bundles across standard CommonJS, ESM, and type definition outputs defined in `package.json` and registry manifests in `jsr.json`. Consumers can import specialized presets directly from subpaths such as `./quick` and `./tiny` to optimize their application build output [package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106). | Export Subpath | Type Definitions | ESM Output | CommonJS Output | Preset Purpose | | -------------- | ---------------- | ---------- | --------------- | -------------- | | `.` | `./dist/types/index.d.ts` | `./dist/index.js` | `./dist/cjs/index.js` | Standard multi-router entry point | | `./quick` | `./dist/types/preset/quick.d.ts` | `./dist/preset/quick.js` | `./dist/cjs/preset/quick.js` | `[[Application Core]]` with `SmartRouter` (Linear + Trie) | | `./tiny` | `./dist/types/preset/tiny.d.ts` | `./dist/preset/tiny.js` | `./dist/cjs/preset/tiny.js` | `[[Application Core]]` with lightweight `PatternRouter` | Sources: [package.json:37-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L67), [jsr.json:8-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L106) ### Architectural Trade-Offs The standard package entry point imports from `./hono`, allowing developers to leverage comprehensive feature sets across middlewares and helpers [src/index.ts:17-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L17-L53). In contrast, specialized presets bypass default router selections by extending `HonoBase` directly with targeted routing engines [src/preset/quick.ts:6-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L6-L23), [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19). > [!NOTE] > The `hono/quick` preset initializes a `SmartRouter` composed of `LinearRouter` and `TrieRouter` instances, whereas `hono/tiny` instantiates a single `PatternRouter` to minimize initialization overhead [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22), [src/preset/tiny.ts:18-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L18-L18). Sources: [src/preset/quick.ts:6-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L6-L23), [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19), [src/index.ts:17-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/index.ts#L17-L53) ## Quick Preset Router Composition ### Smart Router Initialization and Composition The `hono/quick` preset constructs an optimized subclass of `[[Application Core]]` by extending `HonoBase` and instantiating a `SmartRouter` within its constructor [src/preset/quick.ts:13-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L13-L23). Rather than binding to a single routing strategy, `SmartRouter` receives an array containing both a `LinearRouter` and a `TrieRouter` instance [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22). ```typescript export class Hono< E extends Env = BlankEnv, S extends Schema = BlankSchema, BasePath extends string = '/', > extends HonoBase { constructor(options: HonoOptions = {}) { super(options) this.router = new SmartRouter({ routers: [new LinearRouter(), new TrieRouter()], }) } ``` Sources: [src/preset/quick.ts:13-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L13-L23) > [!NOTE] > The `hono/quick` preset relies on module resolution from `../router/linear-router`, `../router/smart-router`, and `../router/trie-router` to assemble its multi-strategy matching engine [src/preset/quick.ts:8-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L8-L10). Sources: [src/preset/quick.ts:8-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L8-L10) ### Fallback Mechanics and Execution Flow | Component Class | Import Path | Role in `SmartRouter` Composition | | --------------- | ----------- | --------------------------------- | | `LinearRouter` | `../router/linear-router` | Fast linear scanning for simpler route tables [src/preset/quick.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L8), [src/preset/quick.ts:21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L21) | | `TrieRouter` | `../router/trie-router` | Prefix tree matching for complex parameter patterns [src/preset/quick.ts:10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L10), [src/preset/quick.ts:21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L21) | | `SmartRouter` | `../router/smart-router` | Composite wrapper managing router selection and fallback [src/preset/quick.ts:9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L9), [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22) | Sources: [src/preset/quick.ts:8-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L8-L10), [src/preset/quick.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts#L20-L22) ## Tiny Preset for Constrained Runtimes ### Pattern-Based Dispatch Mechanics The `hono/tiny` preset configures a minimal application footprint by extending `HonoBase` with the lightweight `PatternRouter` engine [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19). Instantiating `Hono` within this module assigns a `PatternRouter` directly to `this.router`, omitting complex multi-router selection logic and reducing overall binary weight for constrained execution environments [src/preset/tiny.ts:16-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L16-L19). ```typescript export class Hono< E extends Env = BlankEnv, S extends Schema = BlankSchema, BasePath extends string = '/', > extends HonoBase { constructor(options: HonoOptions = {}) { super(options) this.router = new PatternRouter() } } ``` Sources: [src/preset/tiny.ts:11-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L11-L20)] > [!NOTE] > The `hono/tiny` implementation accepts generic type parameters for environment bindings (`Env`), schema validation (`Schema`), and base path prefixes (`BasePath`), passing options directly to the `HonoBase` superclass constructor [src/preset/tiny.ts:11-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L11-L17). Sources: [src/preset/tiny.ts:11-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L11-L17) ### Class and Type Configuration | Exported Symbol | Source Path | Type Definition / Role | | --------------- | ----------- | ---------------------- | | `Hono` | `src/preset/tiny.ts` | Subclass of `HonoBase` enforcing `PatternRouter` [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19) | | `HonoBase` | `../hono-base` | Core routing and middleware execution engine [src/preset/tiny.ts:6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6), [src/preset/tiny.ts:15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L15) | | `PatternRouter` | `../router/pattern-router` | Lightweight pattern-matching router backend [src/preset/tiny.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L8), [src/preset/tiny.ts:18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L18) | | `HonoOptions` | `../hono-base` | Configuration options interface for instantiation [src/preset/tiny.ts:7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L7), [src/preset/tiny.ts:16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L16) | Sources: [src/preset/tiny.ts:6-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts#L6-L19)] ## Package Export Maps and Module Resolution ### Node.js Package Configuration and Conditional Exports The `package.json` file establishes dual CommonJS and ES Module distribution channels alongside TypeScript declaration mappings [package.json:5-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L5-L8), [package.json:37-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L42). The root export configuration maps types, ESM imports, and CommonJS requires for core modules, presets, middleware, helpers, and utilities [package.json:37-144](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L144). | Export Key | Types Path | Import Path (ESM) | Require Path (CJS) | | ---------- | ---------- | ----------------- | ------------------ | | `.` | `./dist/types/index.d.ts` [package.json:39](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L39) | `./dist/index.js` [package.json:40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L40) | `./dist/cjs/index.js` [package.json:41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L41) | | `./request` | `./dist/types/request.d.ts` [package.json:44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L44) | `./dist/request.js` [package.json:45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L45) | `./dist/cjs/request.js` [package.json:46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L46) | | `./tiny` | `./dist/types/preset/tiny.d.ts` [package.json:59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L59) | `./dist/preset/tiny.js` [package.json:60](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L60) | `./dist/cjs/preset/tiny.js` [package.json:61](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L61) | | `./quick` | `./dist/types/preset/quick.d.ts` [package.json:64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L64) | `./dist/preset/quick.js` [package.json:65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L65) | `./dist/cjs/preset/quick.js` [package.json:66](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L66) | | `./compress` | `./dist/types/middleware/compress/index.d.ts` [package.json:114](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L114) | `./dist/middleware/compress/index.js` [package.json:115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L115) | `./dist/cjs/middleware/compress/index.js` [package.json:116](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L116) | Sources: [package.json:37-117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L37-L117) > [!NOTE] > The postbuild script executes `publint` to validate export map correctness, and copies `package.cjs.json` into distribution subdirectories to enforce CommonJS resolution boundaries [package.json:28-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L28-L30). Sources: [package.json:28-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L28-L30) ### JSR and Deno Module Resolution The `jsr.json` manifest defines direct TypeScript source mappings for JSR distribution, targeting Deno and modern edge runtimes [jsr.json:1-106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L1-L106). It enables the `sloppy-imports` unstable flag and specifies compiler options tailored for DOM and Deno namespaces [jsr.json:4-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L4-L7). ```json "exports": { ".": "./src/index.ts", "./request": "./src/request.ts", "./types": "./src/types.ts", "./hono-base": "./src/hono-base.ts", "./tiny": "./src/preset/tiny.ts", "./quick": "./src/preset/quick.ts", "./http-exception": "./src/http-exception.ts", "./basic-auth": "./src/middleware/basic-auth/index.ts", "./bearer-auth": "./src/middleware/bearer-auth/index.ts", "./body-limit": "./src/middleware/body-limit/index.ts", "./ip-restriction": "./src/middleware/ip-restriction/index.ts", "./cache": "./src/middleware/cache/index.ts", "./route": "./src/helper/route/index.ts", "./cookie": "./src/helper/cookie/index.ts", "./accepts": "./src/helper/accepts/index.ts", "./compress": "./src/middleware/compress/index.ts", "./context-storage": "./src/middleware/context-storage/index.ts", "./cors": "./src/middleware/cors/index.ts", "./csrf": "./src/middleware/csrf/index.ts", "./etag": "./src/middleware/etag/index.ts", "./trailing-slash": "./src/middleware/trailing-slash/index.ts", "./html": "./src/helper/html/index.ts", "./css": "./src/helper/css/index.ts", "./jsx": "./src/jsx/index.ts", "./jsx/jsx-dev-runtime": "./src/jsx/jsx-dev-runtime.ts", "./jsx/jsx-runtime": "./src/jsx/jsx-runtime.ts", "./jsx/streaming": "./src/jsx/streaming.ts", "./jsx-renderer": "./src/middleware/jsx-renderer/index.ts", ``` Sources: [jsr.json:8-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L8-L36) Publish configuration within `jsr.json` explicitly includes source files, configuration manifests, and documentation while excluding test files [jsr.json:107-110](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L107-L110). Runtime test configurations like `runtime-tests/deno/deno.json` bind [JSX runtime](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-runtime) imports to local source files and configure standard library dependencies [runtime-tests/deno/deno.json:1-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno/deno.json#L1-L13). Sources: [jsr.json:107-110](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json#L107-L110), [runtime-tests/deno/deno.json:1-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno/deno.json#L1-L13)] ## Bundle Size Auditing and Enforcement To prevent performance regressions and maintain minimal footprints across core distribution files, Hono uses an automated bundle measurement harness driven by `esbuild`. The check script compiles the built entry point `dist/index.js` into an isolated temporary file using production settings, extracts exact byte and kilobyte measurements, and outputs structured benchmark JSON for validation pipelines. ```typescript async function main() { const tempDir = os.tmpdir() const tempFilePath = path.join(tempDir, 'bundle.tmp.js') try { await esbuild.build({ entryPoints: ['dist/index.js'], bundle: true, minify: true, format: 'esm' as esbuild.Format, target: 'es2022', outfile: tempFilePath, }) const bundleSize = fs.statSync(tempFilePath).size const metrics = [] ``` Sources: [perf-measures/bundle-check/scripts/check-bundle-size.ts:6-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L6-L21) | Configuration Property | Target Value | Purpose | | ---------------------- | ------------ | ------- | | `entryPoints` | `['dist/index.js']` | Specifies the compiled core bundle input file [perf-measures/bundle-check/scripts/check-bundle-size.ts:12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L12) | | `bundle` | `true` | Resolves and inlines all internal module dependencies [perf-measures/bundle-check/scripts/check-bundle-size.ts:13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L13) | | `minify` | `true` | Strips whitespace and mangles identifiers to measure production delivery size [perf-measures/bundle-check/scripts/check-bundle-size.ts:14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L14) | | `format` | `'esm'` | Enforces ECMAScript module output format [perf-measures/bundle-check/scripts/check-bundle-size.ts:15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L15) | | `target` | `'es2022'` | Sets the JavaScript language syntax target level [perf-measures/bundle-check/scripts/check-bundle-size.ts:16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L16) | | `outfile` | `tempFilePath` | Writes output to an OS temporary directory path [perf-measures/bundle-check/scripts/check-bundle-size.ts:17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L17) | Sources: [perf-measures/bundle-check/scripts/check-bundle-size.ts:11-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L11-L18) > [!WARNING] > The auditing harness guarantees cleanup by executing file deletion inside a `finally` block, ensuring temporary artifacts are wiped even if the compilation pass encounters errors [perf-measures/bundle-check/scripts/check-bundle-size.ts:45-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L45-L49). Sources: [perf-measures/bundle-check/scripts/check-bundle-size.ts:45-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/perf-measures/bundle-check/scripts/check-bundle-size.ts#L45-L49)] ## Related - [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) - [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) --- ## Technical docs: Router Contracts URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts
Relevant source files The following files were used as context for generating this wiki page: - [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts) - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts) - [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts) - [src/router/reg-exp-router/matcher.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts) - [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts) - [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/router/smart-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts) - [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts) - [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts) - [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts) - [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts) - [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts)
## Overview Hono defines a generic Router Contracts through the `Router` interface, standardizing how route registration and execution path resolution behave across multiple routing backends [Linear and Pattern Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers), [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router), and [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers). By establishing uniform method signatures for adding paths and matching request methods against registered endpoints, the system allows backends like `LinearRouter`, `PatternRouter`, `RegExpRouter`, and `TrieRouter` to be swapped interchangeably inside applications ([Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core)). These contracts establish strict behaviors around immutable matchers and path constraints, such as throwing `UnsupportedPathError` when conflicting route syntaxes occur during compilation or evaluation. Sources: [src/router.ts:25-52](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L25-L52), [src/router.ts:101-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L101-L103), [src/router/linear-router/router.ts:11-143](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L11-L143), [src/router/pattern-router/router.ts:8-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L8-L42), [src/router/reg-exp-router/router.ts:122-204](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L204), [src/router/trie-router/router.ts:5-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L5-L27), [src/router/smart-router/router.ts:4-61](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L4-L61), [src/hono-base.ts:65-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts#L65-L65) ## Unified Router Interface Architecture ### Router Interface Contract The generic `Router` interface establishes the core contract that every routing backend implements. It defines three primary members: a `name` string property identifying the router implementation, an `add` method for registering paths, and a `match` method for executing lookups. ```typescript * Interface representing a router. * * @template T - The type of the handler. */ export interface Router { /** * The name of the router. */ name: string /** * Adds a route to the router. * * @param method - The HTTP method (e.g., 'get', 'post'). * @param path - The path for the route. * @param handler - The handler for the route. */ add(method: string, path: string, handler: T): void /** * Matches a route based on the given method and path. * * @param method - The HTTP method (e.g., 'get', 'post'). * @param path - The path to match. * @returns The result of the match. */ match(method: string, path: string): Result } ``` Sources: [src/router.ts:25-52](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L25-L52) To support this interface uniformly, the module exports constants defining HTTP methods and error messages utilized during route registration and compilation checks. ```typescript * Constant representing all HTTP methods in uppercase. */ export const METHOD_NAME_ALL = 'ALL' as const /** * Constant representing all HTTP methods in lowercase. */ export const METHOD_NAME_ALL_LOWERCASE = 'all' as const /** * Array of supported HTTP methods. */ export const METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch'] as const /** * Error message indicating that a route cannot be added because the matcher is already built. */ export const MESSAGE_MATCHER_IS_ALREADY_BUILT = 'Can not add a route since the matcher is already built.' ``` Sources: [src/router.ts:7-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L7-L23) > [!NOTE] > The `METHOD_NAME_ALL` and `METHOD_NAME_ALL_LOWERCASE` constants represent wildcard HTTP methods ('ALL' and 'all') used to register handlers matching any incoming request method. ### Interface Implementation Registry Different routing strategies fulfill the `Router` contract across the codebase, exporting their constructors or helper utilities from respective entrypoints. | Router Module | Exported Symbols | Description | | :--- | :--- | :--- | | `src/router/reg-exp-router/index.ts` | `RegExpRouter`, `PreparedRegExpRouter`, `buildInitParams`, `serializeInitParams` | Compiles route trees into single regular expressions | | `src/router/pattern-router/index.ts` | `PatternRouter` | Evaluates basic pattern matching for lightweight requirements | | `src/router/trie-router/index.ts` | `TrieRouter` | Traverses path segments using node trees | ```typescript /** * @module * RegExpRouter for Hono. */ export { RegExpRouter } from './router' export { PreparedRegExpRouter, buildInitParams, serializeInitParams } from './prepared-router' ``` Sources: [src/router/reg-exp-router/index.ts:1-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts#L1-L7) ```typescript /** * @module * PatternRouter for Hono. */ ``` Sources: [src/router/pattern-router/index.ts:1-5](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts#L1-L5) ```typescript /** * @module * TrieRouter for Hono. */ export { TrieRouter } from './router' ``` Sources: [src/router/trie-router/index.ts:1-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts#L1-L6) ## Match Result Representations and Parameter Extraction ### Result Data Tuples and Parameter Formats Route resolution yields a `Result` tuple that accommodates two distinct structural layouts depending on the underlying router implementation. Each format pairs matched handlers with parameter mappings or value stashes. ```typescript * Type representing a map of parameter indices. */ export type ParamIndexMap = Record /** * Type representing a stash of parameters. */ export type ParamStash = string[] /** * Type representing a map of parameters. */ export type Params = Record /** * Type representing the result of a route match. * * The result can be in one of two formats: * 1. An array of handlers with their corresponding parameter index maps, followed by a parameter stash. * 2. An array of handlers with their corresponding parameter maps. * * Example: * * [[handler, paramIndexMap][], paramArray] * ```typescript * [ * [ * [middlewareA, {}], // '*' * [funcA, {'id': 0}], // '/user/:id/*' * [funcB, {'id': 0, 'action': 1}], // '/user/:id/:action' * ], * ['123', 'abc'] * ] * ``` * * [[handler, params][]] * ```typescript * [ * [ * [middlewareA, {}], // '*' * [funcA, {'id': '123'}], // '/user/:id/*' * [funcB, {'id': '123', 'action': 'abc'}], // '/user/:id/:action' * ] * ] * ``` */ export type Result = [[T, ParamIndexMap][], ParamStash] | [[T, Params][]] ``` Sources: [src/router.ts:55-99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L55-L99) > [!NOTE] > The first format nests a tuple of `[T, ParamIndexMap][]` alongside a separate `ParamStash` array (`string[]`), allowing parameter values to be indexed numerically. The second format directly associates handlers with fully resolved `Params` dictionaries (`Record`). ### Parameter Data Structures Parameter management relies on specific type definitions for maps and value arrays. The module defines three distinct type aliases to support parameter extraction during route resolution. | Type Name | Definition | Description | | :--- | :--- | :--- | | `ParamIndexMap` | `Record` | Maps parameter name keys to numeric index positions within the parameter stash array. | | `ParamStash` | `string[]` | Ordered array of extracted string parameter values referenced by index maps. | | `Params` | `Record` | Key-value dictionary mapping parameter names directly to their resolved string values. | ```typescript * Type representing a map of parameter indices. */ export type ParamIndexMap = Record /** * Type representing a stash of parameters. */ export type ParamStash = string[] /** * Type representing a map of parameters. */ export type Params = Record ``` Sources: [src/router.ts:55-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L55-L65) ## Shared Routing Errors and Matcher Constraints ### Matcher State Invariants and Error Messages During router lifecycle management, route addition is restricted once matching structures have been compiled or initialized. The module defines a specific constant error message to indicate this constraint violation when attempting modifications after compilation. ```typescript * Error message indicating that a route cannot be added because the matcher is already built. */ export const MESSAGE_MATCHER_IS_ALREADY_BUILT = 'Can not add a route since the matcher is already built.' ``` Sources: [src/router.ts:19-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L19-L23) > [!WARNING] > Attempting to invoke `add` after a router implementation has built its matcher triggers the error message defined by `MESSAGE_MATCHER_IS_ALREADY_BUILT`, freezing route registration to ensure thread-safe and deterministic lookups. ### Unsupported Path Error Semantics When path structures fail validation or fall outside supported syntax patterns during registration or matching, routers throw specialized error types extending standard JavaScript exceptions. ```typescript /** * Error class representing an unsupported path error. */ export class UnsupportedPathError extends Error {} ``` Sources: [src/router.ts:100-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L100-L103) | Error Class / Constant | Underlying Value / Base | Purpose | | :--- | :--- | :--- | | `UnsupportedPathError` | `Error` | Signals that a given route path contains unsupported tokens or structural formatting incompatible with the router backend. | | `MESSAGE_MATCHER_IS_ALREADY_BUILT` | `'Can not add a route since the matcher is already built.'` | Prevents post-initialization mutation of router route tables. | ```typescript export const MESSAGE_MATCHER_IS_ALREADY_BUILT = 'Can not add a route since the matcher is already built.' … */ ``` Sources: [src/router.ts:21-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L21-L22), [src/router.ts:102-102](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L102-L102) ## Route Introspection and Base Path Resolution ### Introspection Helpers and Active Route Selection The routing helper module provides functions to inspect active request contexts and extract matching route metadata. The `matchedRoutes` function accesses the low-level match result stored on the request object using the `GET_MATCH_RESULT` constant symbol, mapping the internal tuple structure to an array of `RouterRoute` definitions. ```typescript export const matchedRoutes = (c: Context): RouterRoute[] => // @ts-expect-error c.req[GET_MATCH_RESULT] is not typed (c.req as unknown)[GET_MATCH_RESULT][0].map(([[, route]]) => route) ``` Sources: [src/helper/route/index.ts:32-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L32-L34) ```typescript export const routePath = (c: Context, index?: number): string => matchedRoutes(c).at(index ?? c.req.routeIndex)?.path ?? '' ``` Sources: [src/helper/route/index.ts:58-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L58-L59) > [!NOTE] > Both `routePath` and `baseRoutePath` accept an optional index argument. This parameter behaves similarly to `Array.prototype.at()`, allowing negative integers to count backward from the end of the matching root collection while defaulting to `c.req.routeIndex`. ```typescript export const baseRoutePath = (c: Context, index?: number): string => matchedRoutes(c).at(index ?? c.req.routeIndex)?.basePath ?? '' ``` Sources: [src/helper/route/index.ts:82-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L82-L83) ### Base Path Resolution and Caching The `basePath` function computes the concrete base path with embedded parameters resolved against the active request URL. It utilizes a private `WeakMap` cache named `basePathCacheMap` to store calculated base paths per `Context` instance and index, avoiding redundant substring matching operations during nested application dispatches. ```typescript const basePathCacheMap: WeakMap> = new WeakMap() export const basePath = (c: Context, index?: number): string => { index ??= c.req.routeIndex const cache = basePathCacheMap.get(c) || [] if (typeof cache[index] === 'string') { return cache[index] } ``` Sources: [src/helper/route/index.ts:106-113](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L106-L113) When the unparsed base route path contains dynamic parameters or wildcards matching `[:*]`, `basePath` splits the path via `splitRoutingPath` and iterates over each segment. It queries pattern matchers using `getPattern` to extract substring lengths directly from `c.req.path`, assembling the final prefix dynamically. Sources: [src/helper/route/index.ts:107-141](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L107-L141) > [!WARNING] > Bypassing index bounds or passing uninitialized request contexts to route introspection helpers will cause lookup failures against `GET_MATCH_RESULT`. Always invoke these utilities within active request handler flows or middleware layers where routing context has been fully established. ### Execution Walkthroughs #### Trace Sequence The resolution of active route paths proceeds through a structured sequence of helper calls. 1. `basePath` checks the `basePathCacheMap` cache using the context and index; on a cache miss, it invokes `baseRoutePath`. 2. `baseRoutePath` calls `matchedRoutes` to retrieve the active route list. 3. `matchedRoutes` reads `(c.req as unknown)[GET_MATCH_RESULT][0]` and maps the internal tuples to return `RouterRoute[]`. ```mermaid sequenceDiagram participant Context as Context (c) participant Helper as src/helper/route/index.ts participant Request as c.req Context->>Helper: basePath(c, index) Helper->>Helper: baseRoutePath(c, index) Helper->>Helper: matchedRoutes(c) Helper->>Request: access GET_MATCH_RESULT symbol Request-->>Helper: return internal match result tuples Helper-->>Context: return resolved path string ``` Sources: [src/helper/route/index.ts:32-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L32-L34), [src/helper/route/index.ts:82-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L82-L83), [src/helper/route/index.ts:107-116](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L107-L116) ## Path Tokenization for Route Group Matching ### Path Splitting and Group Extraction The URL utility module manages route path normalization by tokenizing paths, extracting embedded parameter groups, and restoring them during route matching. The `splitRoutingPath` function coordinates this normalization process by first invoking `extractGroupsFromPath` on the raw route string. ```typescript export const splitRoutingPath = (routePath: string): string[] => { const { groups, path } = extractGroupsFromPath(routePath) const paths = splitPath(path) return replaceGroupMarks(paths, groups) } ``` Sources: [src/utils/url.ts:16-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L16-L21) The `extractGroupsFromPath` function scans the input path for bracketed expressions matching `/\{[^}]+\}/g`. For every discovered group, it generates a placeholder mark using the pattern `@${index}` and stores the pair in an array before returning the modified path string. ```typescript const extractGroupsFromPath = (path: string): { groups: [string, string][]; path: string } => { const groups: [string, string][] = [] path = path.replace(/\{[^}]+\}/g, (match, index) => { const mark = `@${index}` groups.push([mark, match]) return mark }) return { groups, path } } ``` Sources: [src/utils/url.ts:23-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L23-L33) > [!NOTE] > Parameter group extraction prevents forward-slash characters contained inside custom regex definitions (such as `{id:[0-9/]+}`) from breaking segment-based path splitting operations. ```typescript export const splitPath = (path: string): string[] => { const paths = path.split('/') if (paths[0] === '') { paths.shift() } return paths } ``` Sources: [src/utils/url.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L8-L14) ### Group Mark Replacement Once the path is split into individual segments via `splitPath`, the `replaceGroupMarks` function iterates backward through the stored groups to substitute temporary placeholders with their original bracketed definitions. ```typescript const replaceGroupMarks = (paths: string[], groups: [string, string][]): string[] => { for (let i = groups.length - 1; i >= 0; i--) { const [mark] = groups[i] for (let j = paths.length - 1; j >= 0; j--) { if (paths[j].includes(mark)) { paths[j] = paths[j].replace(mark, groups[i][1]) break } } } return paths } ``` Sources: [src/utils/url.ts:35-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L35-L48) > [!WARNING] > Modifying tokenized path arrays directly without running `replaceGroupMarks` will leave orphan `@index` markers intact, corrupting downstream route compilation in [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router) and [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers). ### Execution Walkthroughs #### Trace Sequences ##### Extraction Trace 1. `basePath` calls `splitRoutingPath`. 2. `splitRoutingPath` calls `extractGroupsFromPath`. 3. `extractGroupsFromPath` matches bracketed expressions and populates the groups array. ```mermaid sequenceDiagram participant Helper as basePath participant URLUtils as splitRoutingPath participant Extractor as extractGroupsFromPath Helper->>URLUtils: splitRoutingPath(rp) URLUtils->>Extractor: extractGroupsFromPath(routePath) Extractor-->>URLUtils: return { groups, path } ``` Sources: [src/helper/route/index.ts:120-120](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L120-L120), [src/utils/url.ts:16-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L16-L17), [src/utils/url.ts:23-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L23-L33) ##### Replacement Trace 1. `basePath` calls `splitRoutingPath`. 2. `splitRoutingPath` calls `splitPath` on the cleaned path string. 3. `splitRoutingPath` calls `replaceGroupMarks` to substitute temporary markers. ```mermaid sequenceDiagram participant Helper as basePath participant URLUtils as splitRoutingPath participant Replacer as replaceGroupMarks Helper->>URLUtils: splitRoutingPath(rp) URLUtils->>URLUtils: splitPath(path) URLUtils->>Replacer: replaceGroupMarks(paths, groups) Replacer-->>URLUtils: return normalized paths array ``` Sources: [src/helper/route/index.ts:120-120](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts#L120-L120), [src/utils/url.ts:16-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L16-L20), [src/utils/url.ts:35-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts#L35-L48) ## Related - [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router) - [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers) - [Linear and Pattern Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers) --- ## Technical docs: RegExp Router URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router
Relevant source files The following files were used as context for generating this wiki page: - [src/router/reg-exp-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts) - [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts) - [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts) - [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts) - [src/router/reg-exp-router/matcher.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts) - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts) - [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts) - [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts) - [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts) - [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts) - [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts) - [src/helper/dev/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/dev/index.ts) - [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts) - [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/router/smart-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts) - [src/utils/compress.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/compress.ts)
## Overview The `RegExpRouter` implements the unified [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) interface by compiling registered path structures and HTTP method sets into a single optimized regular expression [src/router/reg-exp-router/router.ts:122-207](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L207). Operating as a core backend option for [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) via SmartRouter, it transforms wildcard patterns, path parameters, and static segments into a radix-style node trie that generates a unified matcher [src/router/reg-exp-router/router.ts:34-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L34-L103), [src/router/reg-exp-router/trie.ts:6-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L6-L73). By consolidating route evaluation, it avoids linear array scans during request dispatching [src/router/reg-exp-router/matcher.ts:10-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L10-L33). Additionally, `PreparedRegExpRouter` supports ahead-of-time serialization and pre-compilation patterns to eliminate runtime startup overhead [src/router/reg-exp-router/prepared-router.ts:9-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L9-L164). Sources: [src/router/reg-exp-router/router.ts:34-207](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L34-L207), [src/router/reg-exp-router/trie.ts:6-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L6-L73), [src/router/reg-exp-router/matcher.ts:10-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L10-L33), [src/router/reg-exp-router/prepared-router.ts:9-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L9-L164) ## Architecture and Routing Model ### Public Router Implementation and State Management The `RegExpRouter` class implements the [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) interface, managing route registration and request matching state through private collections [src/router/reg-exp-router/router.ts:122-130](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L130). During the initialization phase, the router constructs separate storage maps for middleware and terminal routes under the `ALL` HTTP method (METHOD_NAME_ALL) [src/router/reg-exp-router/router.ts:127-130](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L127-L130). ```typescript export class RegExpRouter implements Router { name: string = 'RegExpRouter' #middleware?: Record[]>> #routes?: Record[]>> constructor() { this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) } this.#routes = { [METHOD_NAME_ALL]: Object.create(null) } } // ... } ``` Sources: [src/router/reg-exp-router/router.ts:122-130](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L130) > [!IMPORTANT] > Once a match operation compiles the underlying regular expression, the `#middleware` and `#routes` internal maps become `undefined`. Any subsequent call to `add()` after building will throw an error with `MESSAGE_MATCHER_IS_ALREADY_BUILT`. Sources: [src/router/reg-exp-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L136-L138) ### Route Registration Lifecycle The `add()` method populates internal HTTP method tables, handles optional parameters via `checkOptionalParameter`, and processes wildcard suffix patterns [src/router/reg-exp-router/router.ts:132-204](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L132-L204). When a new HTTP method is encountered for the first time, the router initializes its maps by copying existing entries registered under `ALL` [src/router/reg-exp-router/router.ts:140-147](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L140-L147). | Internal Property / Parameter | Type | Purpose | | :--- | :--- | :--- | | `name` | `string` | Identifies the router backend as `'RegExpRouter'`. | | `#middleware` | `Record[]>>` | Stores registered middleware paths grouped by HTTP method. | | `#routes` | `Record[]>>` | Stores terminal route handlers grouped by HTTP method. | | `METHOD_NAME_ALL` | `string` | Constant designating catch-all HTTP methods (`'ALL'`). | | `nullMatcher` | `Matcher` | Fallback matcher for empty routing tables (`[/^$/, [], Object.create(null)]`). | Sources: [src/router.ts:9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L9), [src/router/reg-exp-router/router.ts:17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L17), [src/router/reg-exp-router/router.ts:122-130](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L122-L130), [src/router/reg-exp-router/router.ts:140-147](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L140-L147) Wildcard patterns ending in `*` are expanded and tested against existing route entries using cached regular expressions built via `buildWildcardRegExp` [src/router/reg-exp-router/router.ts:20-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L20-L28), [src/router/reg-exp-router/router.ts:155-186](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L155-L186). ```typescript function buildWildcardRegExp(path: string): RegExp { return (wildcardRegExpCache[path] ??= new RegExp( path === '*' ? '' : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : '(?:|/.*)' )}$` )) } ``` Sources: [src/router/reg-exp-router/router.ts:20-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L20-L28) ### Matcher Compilation Workflow When request matching occurs, `buildMatcherFromPreprocessedRoutes` sorts paths, separates static and dynamic segments, and delegates structural insertion to a `Trie` instance [src/router/reg-exp-router/router.ts:34-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L34-L82). Static paths are stored directly in a `staticMap` for O(1) lookups, while dynamic paths contribute to a consolidated regular expression [src/router/reg-exp-router/router.ts:43-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L43-L82). ```typescript function buildMatcherFromPreprocessedRoutes( routes: [string, HandlerWithMetadata[]][] ): Matcher { const trie = new Trie() const handlerData: HandlerData[] = [] if (routes.length === 0) { return nullMatcher } ``` Sources: [src/router/reg-exp-router/router.ts:34-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L34-L42) > [!WARNING] > Path insertions that conflict with structural constraints or invalid syntax throw a `PATH_ERROR`, which the router catches and re-throws as an `UnsupportedPathError`. Sources: [src/router/reg-exp-router/router.ts:61-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L61-L65) ## Trie Intermediate Representation ### Path Tokenization and Group Preservation The `Trie` class manages routing structures through a root `Node` instance and a shared context tracking variable indices (`varIndex`) [src/router/reg-exp-router/trie.ts:6-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L6-L8). When a route path is inserted, the `insert()` method first isolates bracketed custom regular expression groups (such as `:id{[0-9]+}`) by replacing them with temporary placeholder markers (`@\i`) [src/router/reg-exp-router/trie.ts:13-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L13-L26). It then tokenizes the modified path using a regular expression that matches named parameters (`:[^\/]+`), wildcard suffixes (`/\*$`), or individual characters, before restoring the original bracketed expressions into the correct token positions [src/router/reg-exp-router/trie.ts:33-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L33-L42). ```typescript const groups: [string, string][] = [] // [mark, original string] for (let i = 0; ; ) { let replaced = false path = path.replace(/\{[^}]+\}/g, (m) => { const mark = `@\\${i}` groups[i] = [mark, m] i++ replaced = true return mark }) if (!replaced) { break } } ``` Sources: [src/router/reg-exp-router/trie.ts:13-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L13-L26) ### Node Graph Insertion and Conflict Checks The `Node` class recursively inserts token arrays into its `#children` record map [src/router/reg-exp-router/node.ts:45-133](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L45-L133). During insertion, tokens are evaluated to determine their pattern types—distinguishing between standalone wildcards (`*`), tail wildcards (`/*`), named parameters with custom expressions, common label patterns (`[^/]+`), and literal characters [src/router/reg-exp-router/node.ts:69-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L69-L78). | Token / Pattern Type | Regular Expression String | Assigned Variable / Purpose | | :--- | :--- | :--- | | `*` (terminal) | `.*` (`ONLY_WILDCARD_REG_EXP_STR`) | Matches all trailing paths without capturing a parameter name. | | `*` (non-terminal) | `[^/]+` (`LABEL_REG_EXP_STR`) | Acts as a generic path segment label. | | `/*` | `(?:|/.*)` (`TAIL_WILDCARD_REG_EXP_STR`) | Matches an optional trailing slash followed by any path content. | | `:label` | `[^/]+` (`LABEL_REG_EXP_STR`) | Captures standard path segments into `paramMap`. | | `:label{expr}` | `expr` (custom regex string) | Validates and captures custom regex patterns; enforces non-capturing group constraints. | Sources: [src/router/reg-exp-router/node.ts:1-3](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L1-L3), [src/router/reg-exp-router/node.ts:69-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L69-L78) > [!CAUTION] > Inserting conflicting segment types into the same Trie node level—such as mixing literal characters with multi-character wildcards or mixing distinct regular expression patterns—immediately throws `PATH_ERROR`. Custom expressions containing capturing groups without non-capturing prefixes (`(?!:\?)`) are also rejected. Sources: [src/router/reg-exp-router/node.ts:87-91](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L87-L91), [src/router/reg-exp-router/node.ts:96-102](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L96-L102), [src/router/reg-exp-router/node.ts:117-124](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L117-L124) ## Pattern Compilation and Radix Merging ### Recursive Regex String Synthesis and Child Key Sorting The `Node` class converts the hierarchical trie structure into a unified regular expression string via the `buildRegExpStr()` method [src/router/reg-exp-router/node.ts:135-161](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L135-L161). Child node keys are retrieved, sorted using the `compareKey` function, and mapped into sub-expressions [src/router/reg-exp-router/node.ts:136-147](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L136-L147). ```typescript function compareKey(a: string, b: string): number { if (a.length === 1) { return b.length === 1 ? (a < b ? -1 : 1) : -1 } if (b.length === 1) { return 1 } // wildcard if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { return 1 } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) { return -1 } // label if (a === LABEL_REG_EXP_STR) { return 1 } else if (b === LABEL_REG_EXP_STR) { return -1 } return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length } ``` Sources: [src/router/reg-exp-router/node.ts:20-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L20-L43) The sorting algorithm establishes strict evaluation precedence by organizing node keys in the following order: literal strings, special custom patterns, common label patterns (`[^/]+`), and wildcards (`.*` or `(?:|/.*)`) [src/router/reg-exp-router/node.ts:14-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L14-L19). ```typescript buildRegExpStr(): string { const childKeys = Object.keys(this.#children).sort(compareKey) const strList = childKeys.map((k) => { const c = this.#children[k] return ( (typeof c.#varIndex === 'number' ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr() ) }) if (typeof this.#index === 'number') { strList.unshift(`#${this.#index}`) } if (strList.length === 0) { return '' } if (strList.length === 1) { return strList[0] } return '(?:' + strList.join('|') + ')' } ``` Sources: [src/router/reg-exp-router/node.ts:135-161](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L135-L161) > [!NOTE] > When multiple child nodes exist at the same level, `buildRegExpStr()` joins them with alternation operators (`|`) wrapped in non-capturing groups `(?:...)`. If a node marks a route termination point (`#index`), its handler identifier is prepended to the string list before alternation synthesis [src/router/reg-exp-router/node.ts:149-160](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L149-L160). Sources: [src/router/reg-exp-router/node.ts:149-160](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts#L149-L160) ### Wildcard Normalization and Root Compilation Wildcard routes and trailing patterns undergo specific normalization before and during trie integration [src/router/reg-exp-router/router.ts:20-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L20-L28). The router maintains a `wildcardRegExpCache` to compile wildcard expressions, translating `/*` suffixes into safe literal escape sequences combined with `(?:|/.*)` optional path matchers [src/router/reg-exp-router/router.ts:19-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L19-L28). ```typescript let wildcardRegExpCache: Record = Object.create(null) function buildWildcardRegExp(path: string): RegExp { return (wildcardRegExpCache[path] ??= new RegExp( path === '*' ? '' : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : '(?:|/.*)' )}$` )) } ``` Sources: [src/router/reg-exp-router/router.ts:19-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts#L19-L28) Once the trie graph is fully populated, `Trie.buildRegExp()` finalizes the compiled string by processing handler markers (`#\d+`), parameter markers (`@\d+`), and wildcard endings (`\.\*\$`) [src/router/reg-exp-router/trie.ts:49-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L49-L73). It constructs `indexReplacementMap` and `paramReplacementMap` lookup structures to align capturing groups with handler indices, returning a fully operational `RegExp` instance anchored with a caret (`^`) [src/router/reg-exp-router/trie.ts:55-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L55-L73). ```typescript buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] { let regexp = this.#root.buildRegExpStr() if (regexp === '') { return [/^$/, [], []] // never match } let captureIndex = 0 const indexReplacementMap: ReplacementMap = [] const paramReplacementMap: ReplacementMap = [] regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => { if (handlerIndex !== undefined) { indexReplacementMap[++captureIndex] = Number(handlerIndex) return '$()' } if (paramIndex !== undefined) { paramReplacementMap[Number(paramIndex)] = ++captureIndex return '' } return '' }) return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap] } ``` Sources: [src/router/reg-exp-router/trie.ts:49-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts#L49-L73) ## Matcher Execution and Param Extraction ### Single-Pass Regex Matching and Static Map Lookups When a request path is evaluated, the `match` function first resolves the appropriate `Matcher` tuple for the HTTP method by checking method-specific matchers or falling back to `METHOD_NAME_ALL` [src/router/reg-exp-router/matcher.ts:10-15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L10-L15). ```typescript export function match, T>(this: R, method: string, path: string): Result { // eslint-disable-next-line @typescript-eslint/no-explicit-any const matchers: MatcherMap = (this as any).buildAllMatchers() const match = ((method, path) => { const matcher = (matchers[method] || matchers[METHOD_NAME_ALL]) as Matcher const staticMatch = matcher[2][path] if (staticMatch) { return staticMatch } ``` Sources: [src/router/reg-exp-router/matcher.ts:10-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L10-L20) Before executing regular expression evaluation, the router checks the `StaticMap` (`matcher[2]`) for an exact path match [src/router/reg-exp-router/matcher.ts:17-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L17-L20). If a static entry exists, it returns the precompiled handler list and empty parameters directly, avoiding regex overhead entirely [src/router/reg-exp-router/matcher.ts:17-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L17-L20). When the path is dynamic, `path.match(matcher[0])` executes a single-pass regular expression match across the compiled routing tree [src/router/reg-exp-router/matcher.ts:22-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L22-L25). ```typescript const match = path.match(matcher[0]) if (!match) { return [[], emptyParam] } const index = match.indexOf('', 1) return [matcher[1][index], match] }) as Router['match'] ``` Sources: [src/router/reg-exp-router/matcher.ts:21-29](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L21-L29) > [!NOTE] > If the regular expression test fails (`!match`), the matcher immediately returns an empty handler list and an empty parameter array `[[], emptyParam]` [src/router/reg-exp-router/matcher.ts:23-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L23-L25). Sources: [src/router/reg-exp-router/matcher.ts:23-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L23-L25) ### Index-to-Handler Dispatch and Capture-Group Extraction Once a successful regex match occurs, the router determines which route branch matched by scanning the match array for the handler index marker [src/router/reg-exp-router/matcher.ts:27-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L27-L28). The expression `match.indexOf('', 1)` finds the empty string boundary or group index corresponding to the active route branch [src/router/reg-exp-router/matcher.ts:27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L27). ```typescript const index = match.indexOf('', 1) return [matcher[1][index], match] ``` Sources: [src/router/reg-exp-router/matcher.ts:27-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L27-L28) The resulting index maps directly to `matcher[1]`, which holds the handler array and pre-mapped parameter keys for that specific route branch [src/router/reg-exp-router/matcher.ts:28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L28). The matched RegExp result array itself is returned alongside the handlers, supplying captured parameter values extracted from dynamic segments [src/router/reg-exp-router/matcher.ts:28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L28). > [!TIP] > After the initial match call executes, `this.match` is dynamically rewritten on the router instance to point directly to the inner closure function, bypassing method lookup overhead on all subsequent requests [src/router/reg-exp-router/matcher.ts:14-32](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L14-L32). Sources: [src/router/reg-exp-router/matcher.ts:14-32](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts#L14-L32) ## Ahead-of-Time Prepared Matching ### Serialization and Pre-compilation Patterns To bypass dynamic route compilation overhead during server startup, `PreparedRegExpRouter` enables ahead-of-time initialization [src/router/reg-exp-router/prepared-router.ts:9-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L9-L17). The helper function `buildInitParams` provisions a temporary `RegExpRouter` instance, registers all target paths against `METHOD_NAME_ALL`, and exports the resulting matcher structures [src/router/reg-exp-router/prepared-router.ts:95-154](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L95-L154). It constructs a `relocateMap` that maps individual paths to their corresponding handler indices and parameter index maps [src/router/reg-exp-router/prepared-router.ts:111-144](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L111-L144). ```typescript export const buildInitParams: (params: { paths: string[] }) => ConstructorParameters = ({ paths }) => { const RegExpRouterWithMatcherExport = class extends RegExpRouter { buildAndExportAllMatchers() { return this.buildAllMatchers() } } const router = new RegExpRouterWithMatcherExport() for (const path of paths) { router.add(METHOD_NAME_ALL, path, path) } const matchers = router.buildAndExportAllMatchers() const all = matchers[METHOD_NAME_ALL] as Matcher const relocateMap: RelocateMap = {} for (const path of paths) { if (path === '/*' || path === '*') { continue } all[1].forEach((list, i) => { list.forEach(([p, map]) => { if (p === path) { if (relocateMap[path]) { relocateMap[path][0][1] = { ...relocateMap[path][0][1], ...map, } } else { relocateMap[path] = [[[], map]] } if (relocateMap[path][0][0].findIndex((j) => j === i) === -1) { relocateMap[path][0][0].push(i) } } }) }) for (const path2 in all[2]) { all[2][path2][0].forEach(([p]) => { if (p === path) { relocateMap[path] ||= [[[]]] const value = path2 === path ? '' : path2 if (relocateMap[path][0][0].findIndex((v) => v === value) === -1) { relocateMap[path][0][0].push(value) } } }) } } for (let i = 0, len = all[1].length; i < len; i++) { all[1][i] = all[1][i] ? [] : (0 as unknown as HandlerData) } for (const path in all[2]) { all[2][path][0] = [] } return [matchers, relocateMap] } ``` Sources: [src/router/reg-exp-router/prepared-router.ts:95-154](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L95-L154) The companion utility `serializeInitParams` translates these compilation artifacts into stringified JSON formats [src/router/reg-exp-router/prepared-router.ts:156-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L156-L165). To preserve native regular expression objects across serialization boundaries, it converts `RegExp` instances into tagged string placeholders (`##...##`) and restores them via regex replacement during output generation [src/router/reg-exp-router/prepared-router.ts:160-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L160-L164). ```typescript export const serializeInitParams: ( params: ConstructorParameters ) => string = ([matchers, relocateMap]) => { // Embed the regular expression as a result of `toString()` so that it can be evaluated as JavaScript. const matchersStr = JSON.stringify(matchers, (_, value) => value instanceof RegExp ? `##${value.toString()}##` : value ).replace(/"##(.+?)##"/g, (_, str) => str.replace(/\\\\/g, '\\')) const relocateMapStr = JSON.stringify(relocateMap) return `[${matchersStr},${relocateMapStr}]` } ``` Sources: [src/router/reg-exp-router/prepared-router.ts:156-165](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L156-L165) ### Runtime Mechanics and Relocation Maps At runtime, `PreparedRegExpRouter` accepts precompiled `MatcherMap` and `RelocateMap` collections directly through its constructor [src/router/reg-exp-router/prepared-router.ts:14-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L14-L17). When additional routes are added dynamically via `add`, the router references the `relocateMap` to insert handlers into pre-allocated matcher slots without rebuilding the trie or re-synthesizing regular expression patterns [src/router/reg-exp-router/prepared-router.ts:47-86](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L47-L86). ```typescript add(method: string, path: string, handler: T) { if (!this.#matchers[method]) { const all = this.#matchers[METHOD_NAME_ALL] as Matcher const staticMap = {} as StaticMap for (const key in all[2]) { staticMap[key] = [all[2][key][0].slice(), emptyParam] as Result } this.#matchers[method] = [ all[0], all[1].map((list) => (Array.isArray(list) ? list.slice() : 0)) as HandlerData[], staticMap, ] } if (path === '/*' || path === '*') { const handlerData: [T, ParamIndexMap] = [handler, {}] if (method === METHOD_NAME_ALL) { for (const m in this.#matchers) { this.#addWildcard(m, handlerData) } } else { this.#addWildcard(method, handlerData) } return } const data = this.#relocateMap[path] if (!data) { throw new Error(`Path ${path} is not registered`) } for (const [indexes, map] of data) { if (method === METHOD_NAME_ALL) { for (const m in this.#matchers) { this.#addPath(m, path, handler, indexes, map) } } else { this.#addPath(method, path, handler, indexes, map) } } } ``` Sources: [src/router/reg-exp-router/prepared-router.ts:47-86](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L47-L86) > [!WARNING] > If a route path is registered via `add` that was not included in the initial path array passed to `buildInitParams`, the router throws an error stating that the path is not registered [src/router/reg-exp-router/prepared-router.ts:73-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L73-L76). Sources: [src/router/reg-exp-router/prepared-router.ts:73-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L73-L76) | Parameter / Property | Type | Description | | :--- | :--- | :--- | | `#matchers` | `MatcherMap` | Method-indexed collection containing compiled regular expressions, handler lists, and static maps [src/router/reg-exp-router/prepared-router.ts:9-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L9-L17) | | `#relocateMap` | `RelocateMap` | Mapping of paths to route index arrays and parameter index configurations [src/router/reg-exp-router/prepared-router.ts:7-12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L7-L12) | | `buildInitParams` | `Function` | Pre-builds matchers and computes relocation targets from a set of paths [src/router/reg-exp-router/prepared-router.ts:95-97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L95-L97) | | `serializeInitParams` | `Function` | Serializes matchers and relocation maps into an evaluable string representation [src/router/reg-exp-router/prepared-router.ts:156-158](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L156-L158) | Sources: [src/router/reg-exp-router/prepared-router.ts:7-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L7-L17), [src/router/reg-exp-router/prepared-router.ts:95-97](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L95-L97), [src/router/reg-exp-router/prepared-router.ts:156-158](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts#L156-L158) ## Related - [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) - [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers) --- ## Technical docs: Trie and Smart Routers URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers
Relevant source files The following files were used as context for generating this wiki page: - [src/router/smart-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts) - [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts) - [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts) - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts) - [src/router/reg-exp-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts) - [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts) - [src/router/reg-exp-router/matcher.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts) - [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts) - [src/helper/dev/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/dev/index.ts) - [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/utils/ipaddr.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts) - [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [src/helper/ssg/utils.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/utils.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts) - [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts)
## Overview Hono's `TrieRouter` and `SmartRouter` deliver hierarchical prefix routing and dynamic dispatch across multiple matching backends. `TrieRouter` manages route registration through tree node insertion, supporting optional parameter expansion, path segment tokenization, and recursive handler set collection. To combine different routing strategies, `SmartRouter` aggregates multiple router instances, delegating registration to each candidate until a successful match occurs and locking onto the winning backend for subsequent requests. Sources: [src/router/smart-router/router.ts:4-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L4-L70), [src/router/trie-router/node.ts:25-112](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L25-L112), [src/router/trie-router/router.ts:5-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L5-L27) ## TrieRouter Architecture and Route Registration ### Public Interface and Root Node Management `TrieRouter` implements the unified `Router` interface, identifying itself via the `name` property set to `'TrieRouter'`. The class initializes a private root `#node` instance of type `Node` inside its constructor to anchor the entire route prefix tree. ```typescript export class TrieRouter implements Router { name: string = 'TrieRouter' #node: Node constructor() { this.#node = new Node() } ... ``` Sources: [src/router/trie-router/router.ts:5-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L5-L11) ### Optional Parameter Expansion and Route Insertion When adding routes through the `add(method, path, handler)` method, `TrieRouter` inspects the incoming route path using `checkOptionalParameter(path)`. If optional parameters are present, the utility returns an array of expanded path variations; the router iterates over these results and inserts each individual variation into the root node. If no optional parameters are detected, the path is inserted directly. ```typescript add(method: string, path: string, handler: T) { const results = checkOptionalParameter(path) if (results) { for (let i = 0, len = results.length; i < len; i++) { this.#node.insert(method, results[i], handler) } return } this.#node.insert(method, path, handler) } ``` Sources: [src/router/trie-router/router.ts:13-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L13-L23) > [!NOTE] > `checkOptionalParameter` handles path patterns containing optional segments by generating all possible route combinations, ensuring each variant is separately registered in the prefix tree. Sources: [src/router/trie-router/router.ts:14-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L14-L20) ### Route Matching Delegation Incoming request matching delegates execution directly to the root node's `search` method, forwarding both the HTTP `method` and request `path` and returning a resolved `Result` structure containing matched handlers and captured parameters. ```typescript match(method: string, path: string): Result { return this.#node.search(method, path) } ``` Sources: [src/router/trie-router/router.ts:25-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts#L25-L27) ## Trie Node Structure and Insertion ### Node Fields and Constructor Initialization The `Node` class maintains the internal state of the prefix tree using private fields. Each node tracks its registered methods, child nodes, extracted routing patterns, insertion order counters, and parameter records. ```typescript export class Node { #methods: Record>[] #children: Record> #patterns: Pattern[] #order: number = 0 #params: Record = emptyParams constructor(method?: string, handler?: T, children?: Record>) { this.#children = children || Object.create(null) this.#methods = [] if (method && handler) { const m: Record> = Object.create(null) m[method] = { handler, possibleKeys: [], score: 0 } this.#methods = [m] } this.#patterns = [] } ``` Sources: [src/router/trie-router/node.ts:25-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L25-L42) > [!NOTE] > `emptyParams` is initialized via `Object.create(null)` to provide a prototype-free parameter dictionary. Sources: [src/router/trie-router/node.ts:16-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L16-L16) ### Path Segment Tokenization and Pattern Extraction During route insertion, `insert(method, path, handler)` increments the node order counter and splits the routing path into individual segments using `splitRoutingPath(path)`. It iterates through each segment, calling `getPattern(p, nextP)` to extract parameter and wildcard patterns. ```typescript insert(method: string, path: string, handler: T): Node { this.#order = ++this.#order // eslint-disable-next-line @typescript-eslint/no-this-alias let curNode: Node = this const parts = splitRoutingPath(path) const possibleKeys: string[] = [] for (let i = 0, len = parts.length; i < len; i++) { const p: string = parts[i] const nextP = parts[i + 1] const pattern = getPattern(p, nextP) const key = Array.isArray(pattern) ? pattern[0] : p if (key in curNode.#children) { curNode = curNode.#children[key] if (pattern) { possibleKeys.push(pattern[1]) } continue } ``` Sources: [src/router/trie-router/node.ts:44-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L44-L65) ### Recursive Tree Construction and Handler Binding If a segment key already exists within `curNode.#children`, traversal descends into that child node. Otherwise, a new `Node` instance is instantiated and registered. Extracted patterns are pushed to `#patterns`, and final handler sets are appended to `#methods` with deduplicated `possibleKeys` and an insertion order score. ```typescript curNode.#children[key] = new Node() if (pattern) { curNode.#patterns.push(pattern) possibleKeys.push(pattern[1]) } curNode = curNode.#children[key] } curNode.#methods.push({ [method]: { handler, possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i), score: this.#order, }, }) return curNode } ``` Sources: [src/router/trie-router/node.ts:66-85](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L66-L85) > [!WARNING] > Handler sets filter `possibleKeys` using `a.indexOf(v) === i` to prevent duplicate parameter keys within the same handler registration block. Sources: [src/router/trie-router/node.ts:76-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L76-L82) ## Hierarchical Path Traversal and Matching ### Recursive Search Execution and Queue Management Path lookup begins by invoking `search(method, path)` on the root node, which splits the request path using `splitPath(path)` and initializes a traversal queue of active nodes (`curNodes`) alongside `curNodesQueue` for handling multi-segment regular expression parameter matches. ```typescript search(method: string, path: string): [[T, Params][]] { const handlerSets: HandlerParamsSet[] = [] this.#params = emptyParams // eslint-disable-next-line @typescript-eslint/no-this-alias const curNode: Node = this let curNodes = [curNode] const parts = splitPath(path) const curNodesQueue: Node[][] = [] const len = parts.length let partOffsets: number[] | null = null ``` Sources: [src/router/trie-router/node.ts:114-126](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L114-L126) ### Static Child Lookup and Wildcard Handling During iteration over path segments, the router checks static child nodes via `node.#children[part]`. When reaching the final path segment on a matching child, it evaluates trailing wildcard children (`nextNode.#children['*']`) and pushes matching handler sets into the accumulation array. ```typescript for (let i = 0; i < len; i++) { const part: string = parts[i] const isLast = i === len - 1 const tempNodes: Node[] = [] for (let j = 0, len2 = curNodes.length; j < len2; j++) { const node = curNodes[j] const nextNode = node.#children[part] if (nextNode) { nextNode.#params = node.#params if (isLast) { // '/hello/*' => match '/hello' if (nextNode.#children['*']) { this.#pushHandlerSets(handlerSets, nextNode.#children['*'], method, node.#params) } this.#pushHandlerSets(handlerSets, nextNode, method, node.#params) } else { tempNodes.push(nextNode) } } ``` Sources: [src/router/trie-router/node.ts:127-148](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L127-L148) > [!NOTE] > Wildcard patterns (`*`) directly inspect child nodes keyed by `*`, pushing their associated handler sets and enqueuing the wildcard astNode for subsequent path segments. Sources: [src/router/trie-router/node.ts:153-163](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L153-L163) ### Parameter Capture and Regular Expression Matchers Nodes with patterns evaluate parameters and regular expressions against the remaining path string using precomputed part offsets. If a regular expression matcher succeeds, captured values populate the parameters dictionary and child nodes are scheduled via `curNodesQueue`. ```typescript const [key, name, matcher] = pattern if (!part && !(matcher instanceof RegExp)) { continue } const child = node.#children[key] // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js if (matcher instanceof RegExp) { if (partOffsets === null) { partOffsets = new Array(len) let offset = path[0] === '/' ? 1 : 0 for (let p = 0; p < len; p++) { partOffsets[p] = offset offset += parts[p].length + 1 } } const restPathString = path.substring(partOffsets[i]) const m = matcher.exec(restPathString) if (m) { params[name] = m[0] this.#pushHandlerSets(handlerSets, child, method, node.#params, params) if (hasChildren(child.#children)) { child.#params = params const componentCount = m[0].match(/\//)?.length ?? 0 const targetCurNodes = (curNodesQueue[componentCount] ||= []) targetCurNodes.push(child) } continue } } if (matcher === true || matcher.test(part)) { params[name] = part if (isLast) { ``` Sources: [src/router/trie-router/node.ts:165-203](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L165-L203) ### Handler Set Collection The `#pushHandlerSets` helper method resolves method-specific handlers or `METHOD_NAME_ALL` fallbacks, binds parameter dictionaries from `possibleKeys`, and populates the output `handlerSets` collection. ```typescript #pushHandlerSets( handlerSets: HandlerParamsSet[], node: Node, method: string, nodeParams: Record, params?: Record ): void { for (let i = 0, len = node.#methods.length; i < len; i++) { const m = node.#methods[i] const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet const processedSet: Record = {} if (handlerSet !== undefined) { handlerSet.params = Object.create(null) handlerSets.push(handlerSet) if (nodeParams !== emptyParams || (params && params !== emptyParams)) { for (let i = 0, len = handlerSet.possibleKeys.length; i < len; i++) { const key = handlerSet.possibleKeys[i] const processed = processedSet[handlerSet.score] handlerSet.params[key] = params?.[key] && !processed ? params[key] : (nodeParams[key] ?? params?.[key]) processedSet[handlerSet.score] = true } } } } } ``` Sources: [src/router/trie-router/node.ts:87-112](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L87-L112) > [!WARNING] > Parameter inheritance checks `nodeParams` against `params` using `processedSet` deduplication flags to ensure route parameters maintain correct scope across hierarchical child transitions. Sources: [src/router/trie-router/node.ts:97-110](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts#L97-L110) ## SmartRouter Architecture and Routing Backends ### Multi-Router Aggregation and Registration Contract The `SmartRouter` class implements the unified `Router` interface by aggregating an array of candidate router backends via its constructor initialization parameter (`init.routers`). During the registration phase, calling `add(method, path, handler)` pushes route tuples `[method, path, handler]` into the internal `#routes` collection. If route addition is attempted after the matcher has already been built, it throws an error with the message defined by `MESSAGE_MATCHER_IS_ALREADY_BUILT`. ```typescript export class SmartRouter implements Router { name: string = 'SmartRouter' #routers: Router[] = [] #routes?: [string, string, T][] = [] constructor(init: { routers: Router[] }) { this.#routers = init.routers } add(method: string, path: string, handler: T) { if (!this.#routes) { throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT) } this.#routes.push([method, path, handler]) } ``` Sources: [src/router/smart-router/router.ts:4-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L4-L20) > [!WARNING] > Calling `add()` after matching has been evaluated throws an error because `#routes` is set to `undefined` once an active router locks in. Sources: [src/router/smart-router/router.ts:13-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L13-L19), [src/router/smart-router/router.ts:48-48](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L48-L48) ### Routing Delegation and Matcher Locking When `match(method, path)` is invoked, `SmartRouter` iterates through the candidate routers in `#routers`, populating each candidate with all accumulated routes from `#routes` and testing them sequentially. If an `UnsupportedPathError` occurs on a candidate router, the loop catches the exception, ignores it with `continue`, and falls back to the next available router backend. ```typescript match(method: string, path: string): Result { if (!this.#routes) { throw new Error('Fatal error') } const routers = this.#routers const routes = this.#routes const len = routers.length let i = 0 let res for (; i < len; i++) { const router = routers[i] try { for (let i = 0, len = routes.length; i < len; i++) { router.add(...routes[i]) } res = router.match(method, path) } catch (e) { if (e instanceof UnsupportedPathError) { continue } throw e } this.match = router.match.bind(router) this.#routers = [router] this.#routes = undefined break } ``` Sources: [src/router/smart-router/router.ts:21-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L21-L51) > [!TIP] > Upon a successful match, `SmartRouter` mutates its own prototype methods and state by binding `this.match` directly to the winning `router.match`, reducing `#routers` to a single-element array containing the active router, and clearing `#routes`. Sources: [src/router/smart-router/router.ts:46-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L46-L49) ### Router State Properties | Property / Method | Type / Signature | Description | | :--- | :--- | :--- | | `name` | `string` | Identifies the router name, initialized as `'SmartRouter'` and updated to include the active router name post-selection (e.g. `SmartRouter + RegExpRouter`). | | `#routers` | `Router[]` | Internal array of candidate routing backends provided at instantiation, narrowing down to the single active router upon successful execution. | | `#routes` | `[string, string, T][] \| undefined` | Temporary storage holding registered route tuples before matcher locking; set to `undefined` once a router successfully handles a match. | | `activeRouter` | `Router` | Getter returning the single active router instance once routing has locked in, throwing an error if routes are still pending or multiple routers remain. | ```typescript export class SmartRouter implements Router { name: string = 'SmartRouter' #routers: Router[] = [] #routes?: [string, string, T][] = [] constructor(init: { routers: Router[] }) { this.#routers = init.routers } ``` Sources: [src/router/smart-router/router.ts:4-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L4-L11), [src/router/smart-router/router.ts:63-69](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L63-L69) ## Dynamic Router Selection and Fallback ### Heuristic Selection on First Match `SmartRouter` resolves which underlying router backend handles incoming traffic dynamically during the initial call to `match(method, path)`. It iterates through each candidate router in `#routers`, replaying all buffered route tuples from `#routes` into the candidate via its `add()` method, and immediately attempts to match the target request. If a candidate router successfully executes the match without throwing an `UnsupportedPathError` or other exceptions, selection halts immediately via a `break` statement. ```typescript const routers = this.#routers const routes = this.#routes const len = routers.length let i = 0 let res for (; i < len; i++) { const router = routers[i] try { for (let i = 0, len = routes.length; i < len; i++) { router.add(...routes[i]) } res = router.match(method, path) } catch (e) { if (e instanceof UnsupportedPathError) { continue } throw e } this.match = router.match.bind(router) this.#routers = [router] this.#routes = undefined break } ``` Sources: [src/router/smart-router/router.ts:26-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L26-L50) > [!WARNING] > If all candidate routers fail to match or throw unhandled exceptions, the outer loop completes without breaking (`i === len`), triggering a fatal error throw that halts execution. Sources: [src/router/smart-router/router.ts:52-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L52-L55) ### UnsupportedPathError Handling and Matcher Locking During heuristic evaluation, candidate routers may encounter path syntax or expression structures they cannot process, throwing an `UnsupportedPathError`. The `try...catch` block inspects caught errors; if `e instanceof UnsupportedPathError` is true, the error is suppressed, and execution continues to the next candidate router in the sequence. Any other error type is rethrown immediately. ```typescript try { for (let i = 0, len = routes.length; i < len; i++) { router.add(...routes[i]) } res = router.match(method, path) } catch (e) { if (e instanceof UnsupportedPathError) { continue } throw e } ``` Sources: [src/router/smart-router/router.ts:34-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L34-L44) > [!TIP] > Once a candidate successfully matches, `SmartRouter` locks its matcher by reassigning `this.match` to bind directly to the winning `router.match`, collapsing `#routers` to a single-element array containing only the active router, setting `#routes` to `undefined`, and updating `this.name` to reflect the active backend (e.g., `SmartRouter + RegExpRouter`). Subsequent requests bypass heuristic iteration entirely. Sources: [src/router/smart-router/router.ts:46-58](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts#L46-L58) ## Related - [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) - [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router) --- ## Technical docs: Linear and Pattern Routers URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/linear-and-pattern-routers
Relevant source files The following files were used as context for generating this wiki page: - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts) - [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts) - [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/router/pattern-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/index.ts) - [src/router/reg-exp-router/matcher.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/matcher.ts) - [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts) - [src/preset/tiny.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/tiny.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts) - [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/router/smart-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/router.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/router/reg-exp-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/index.ts) - [src/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts) - [src/router/reg-exp-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts) - [src/router/reg-exp-router/trie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/trie.ts) - [src/router/trie-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/index.ts) - [src/router/smart-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/smart-router/index.ts)
## Overview Linear and Pattern routers provide lightweight path-matching backends designed to minimize bundle footprints and execution overhead in constrained environments. Operating as alternative routing engines alongside [Trie and Smart Routers](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/trie-and-smart-routers) and [RegExp Router](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/regexp-router), these implementations satisfy the unified [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) interface while trading complex trie structures and regex compilation for straightforward linear scanning or direct pattern compilation. By storing routes in linear arrays or evaluating dynamic path segments via native regular expressions, they power compact distribution builds such as `[[Presets and Builds]]` while seamlessly integrating with the core routing lifecycle. Sources: [src/router/linear-router/router.ts:11-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L11-L23), [src/router/pattern-router/router.ts:8-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L8-L42), [src/router.ts:29-52](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router.ts#L29-L52) ## Minimalist Router Architecture and Tradeoffs ### Architectural Roles `LinearRouter` and `PatternRouter` implement the unified `Router` interface through straightforward, dependency-free mechanisms designed for minimal code size and memory overhead. `LinearRouter` stores registered routes inside a private array (`#routes: [string, string, T][]`), processing them sequentially during route matching without compiling regular expressions at definition time. Conversely, `PatternRouter` compiles path definitions directly into native `RegExp` instances upon registration, storing them alongside methods in its `#routes` array. Sources: [src/router/linear-router/router.ts:11-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L11-L23), [src/router/pattern-router/router.ts:8-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L8-L42) ### Design Tradeoffs and Limitations Both routers balance implementation simplicity against runtime performance characteristics. Because `LinearRouter` evaluates path segments and substring positions via string index checks (`indexOf`) and custom iteration loops, it avoids regex compilation overhead during initialization but incurs linear scan costs ($O(N)$) proportional to the registered route count during request matching. `PatternRouter` delegates matching directly to the JavaScript engine's regex execution engine using named capture groups (`match.groups`), but both routers enforce strict structural boundaries on path syntax. When confronted with unsupported path combinations—such as combining labels and wildcards within the same route path—both implementations throw an `UnsupportedPathError`. Sources: [src/router/linear-router/router.ts:25-143](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L25-L143), [src/router/pattern-router/router.ts:44-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L44-L59) > [!WARNING] > Combining wildcard characters (`*`) and labeled parameters (`:name`) within a single route path triggers an `UnsupportedPathError` in both `LinearRouter` and `PatternRouter`. Sources: [src/router/linear-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L136-L138), [src/router/pattern-router/router.ts:33-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L33-L41) ## Linear Route Registration and Execution ### Internal Storage and Route Registration `LinearRouter` implements the `Router` interface by maintaining a private tuple array `#routes: [string, string, T][]` that stores the HTTP method, route pattern, and handler for every registered endpoint. When `add(method, path, handler)` is invoked, the router checks the incoming path for optional parameter syntax via `checkOptionalParameter(path)`. If optional parameters expand the path definition into multiple variations, each resulting path is appended as a distinct tuple entry into `#routes`. ```typescript export class LinearRouter implements Router { name: string = 'LinearRouter' #routes: [string, string, T][] = [] add(method: string, path: string, handler: T) { for ( let i = 0, paths = checkOptionalParameter(path) || [path], len = paths.length; i < len; i++ ) { this.#routes.push([method, paths[i], handler]) } } ``` Sources: [src/router/linear-router/router.ts:11-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L11-L23) ### Sequential Scanning and Matching Branches During `match(method, path)`, `LinearRouter` iterates through `#routes` using a labeled loop (`ROUTES_LOOP`) to evaluate every registered route sequentially. Each candidate tuple's method is tested for an exact match against the incoming request method or the catch-all constant `METHOD_NAME_ALL`. If the method matches, the evaluation branches based on the structural characteristics of the `routePath` string: static paths, trailing or embedded wildcards, labeled parameters, or combined wildcards and labels. ```typescript match(method: string, path: string): Result { const handlers: [T, Params][] = [] ROUTES_LOOP: for (let i = 0, len = this.#routes.length; i < len; i++) { const [routeMethod, routePath, handler] = this.#routes[i] if (routeMethod === method || routeMethod === METHOD_NAME_ALL) { if (routePath === '*' || routePath === '/*') { handlers.push([handler, emptyParams]) continue } const hasStar = routePath.indexOf('*') !== -1 const hasLabel = routePath.indexOf(':') !== -1 if (!hasStar && !hasLabel) { if (routePath === path || routePath + '/' === path) { handlers.push([handler, emptyParams]) } ``` Sources: [src/router/linear-router/router.ts:25-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L25-L40) | Route Type Condition | Path Structure Indicators | Parameter Extraction Mechanism | | :--- | :--- | :--- | | Static Route | `!hasStar && !hasLabel` | `emptyParams` (no parameters) | | Wildcard Route | `hasStar && !hasLabel` | `emptyParams` via substring and slash checks | | Labeled Parameter Route | `hasLabel && !hasStar` | `Record` via `splitPathRe` and regex indices | | Unsupported Combination | `hasLabel && hasStar` | Throws `UnsupportedPathError` | ```typescript const hasStar = routePath.indexOf('*') !== -1 const hasLabel = routePath.indexOf(':') !== -1 if (!hasStar && !hasLabel) { if (routePath === path || routePath + '/' === path) { handlers.push([handler, emptyParams]) } } else if (hasStar && !hasLabel) { const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 42 const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe) const lastIndex = parts.length - 1 for (let j = 0, pos = 0, len = parts.length; j < len; j++) { const part = parts[j] const index = path.indexOf(part, pos) if (index !== pos) { continue ROUTES_LOOP } pos += part.length if (j === lastIndex) { if ( !endsWithStar && pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47) ) { continue ROUTES_LOOP } } else { const index = path.indexOf('/', pos) if (index === -1) { continue ROUTES_LOOP } pos = index } } handlers.push([handler, emptyParams]) } else if (hasLabel && !hasStar) { const params: Record = Object.create(null) const parts = routePath.match(splitPathRe) as string[] const lastIndex = parts.length - 1 for (let j = 0, pos = 0, len = parts.length; j < len; j++) { if (pos === -1 || pos >= path.length) { continue ROUTES_LOOP } const part = parts[j] if (part.charCodeAt(1) === 58) { if (path.charCodeAt(pos) !== 47) { continue ROUTES_LOOP } // /:label let name = part.slice(2) let value if (name.charCodeAt(name.length - 1) === 125) { // :label{pattern} const openBracePos = name.indexOf('{') const next = parts[j + 1] const lookahead = next && next[1] !== ':' && next[1] !== '*' ? `(?=${next})` : '' const pattern = name.slice(openBracePos + 1, -1) + lookahead const restPath = path.slice(pos + 1) const match = new RegExp(pattern, 'd').exec(restPath) as RegExpMatchArrayWithIndices if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) { continue ROUTES_LOOP } name = name.slice(0, openBracePos) value = restPath.slice(...match.indices[0]) pos += match.indices[0][1] + 1 } else { let endValuePos = path.indexOf('/', pos + 1) if (endValuePos === -1) { if (pos + 1 === path.length) { continue ROUTES_LOOP } endValuePos = path.length } value = path.slice(pos + 1, endValuePos) pos = endValuePos } ``` Sources: [src/router/linear-router/router.ts:35-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L35-L138) > [!NOTE] > `LinearRouter` does not halt execution upon finding the first matching route; it continues scanning the entire `#routes` array and collects all matching handlers into a results array. Sources: [src/router/linear-router/router.ts:25-143](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L25-L143) ## Pattern Matching and Dynamic Evaluation ### Path Pattern Compilation and Segment Parsing `PatternRouter` registers routes by parsing path strings into compiled regular expressions stored in `#routes: Route[]`, where each tuple contains `[RegExp, string, T]` representing the compiled pattern, HTTP method, and handler. When `add(method, path, handler)` runs, it checks whether `path` ends with an asterisk and strips `/*` if present. If `path` ends with a question mark, it strips the `?` and recursively invokes `this.add` on the path with the final segment removed via `path.replace(/\/[^/]+$/, '')`. ```typescript add(method: string, path: string, handler: T) { const endsWithWildcard = path.at(-1) === '*' if (endsWithWildcard) { path = path.slice(0, -2) } if (path.at(-1) === '?') { path = path.slice(0, -1) this.add(method, path.replace(/\/[^/]+$/, ''), handler) } ``` Sources: [src/router/pattern-router/router.ts:12-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L12-L20) The router splits and transforms the path into regex tokens using `path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g)`. Each matched segment is mapped: labeled parameters matching `^\/:([^{]+)(?:{(.*)})?` compile into named capture groups `/(?<${match[1]}>${match[2] || '[^/]+'})`, wildcard segments (`/*`) translate to `/[^/]+`, and static segments escape special characters using `/[.\\+*[^\]$()]/g`. The resulting parts are joined between `^` and `/?$` (or `$/` if ending with a wildcard) to instantiate the `RegExp` object. ```typescript const parts = (path.match(/\/?(:\w+(?:{(?:(?:{[\d,]+})|[^}])+})?)|\/?[^\/\?]+/g) || []).map( (part) => { const match = part.match(/^\/:([^{]+)(?:{(.*)})?/) return match ? `/(?<${match[1]}>${match[2] || '[^/]+'})` : part === '/*' ? '/[^/]+' : part.replace(/[.\\+*[^\]$()]/g, '\\$&') } ) try { this.#routes.push([ new RegExp(`^${parts.join('')}${endsWithWildcard ? '' : '/?$'}`), method, handler, ]) ``` Sources: [src/router/pattern-router/router.ts:21-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L21-L38) > [!TIP] > Custom regex constraints inside route parameters—such as numeric bounds or character classes defined in curly braces—are preserved directly during segment extraction and compiled into the named capture group expression. Sources: [src/router/pattern-router/router.ts:24-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L24-L26) ### Request Match Execution and Parameter Extraction During `match(method, path)`, `PatternRouter` initializes an empty `handlers: [T, Params][]` array and loops through every entry in `#routes`. It tests each route method against the incoming `method` or `METHOD_NAME_ALL`. When the method matches, it executes the compiled regex pattern against the request `path`. If `pattern.exec(path)` succeeds, it pushes the handler and extracted `match.groups` (falling back to `emptyParams` created via `Object.create(null)`) into the handlers array, returning `[handlers]` upon completion. ```typescript match(method: string, path: string): Result { const handlers: [T, Params][] = [] for (let i = 0, len = this.#routes.length; i < len; i++) { const [pattern, routeMethod, handler] = this.#routes[i] if (routeMethod === method || routeMethod === METHOD_NAME_ALL) { const match = pattern.exec(path) if (match) { handlers.push([handler, match.groups || emptyParams]) } } } return [handlers] } ``` Sources: [src/router/pattern-router/router.ts:44-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L44-L59) ## Path Support and Fallback Errors ### Handling of Unsupported Syntax and Optional Parameters Both `LinearRouter` and `PatternRouter` enforce specific path composition rules and handle optional trailing parameters during route registration. In `LinearRouter`, the `add` method uses `checkOptionalParameter(path)` from shared URL utilities to expand optional path variations before pushing them into the `#routes` array. ```typescript add(method: string, path: string, handler: T) { for ( let i = 0, paths = checkOptionalParameter(path) || [path], len = paths.length; i < len; i++ ) { this.#routes.push([method, paths[i], handler]) } } ``` Sources: [src/router/linear-router/router.ts:15-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L15-L23) In `PatternRouter`, optional parameters ending with a question mark (`?`) are processed during registration by stripping the trailing `?` character and recursively invoking `this.add` with the preceding path segment removed via `path.replace(/\/[^/]+$/, '')`. ```typescript if (path.at(-1) === '?') { path = path.slice(0, -1) this.add(method, path.replace(/\/[^/]+$/, ''), handler) } ``` Sources: [src/router/pattern-router/router.ts:17-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L17-L20) > [!WARNING] > Combining labeled parameters and wildcards within the same route path in `LinearRouter` (`hasLabel && hasStar`) is unsupported and explicitly triggers an error. Sources: [src/router/linear-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L136-L138) ### Throwing of UnsupportedPathError When path compilation or syntax evaluation encounters malformed expressions or unsupported combinations, both routers throw an `UnsupportedPathError` imported from the core router module. In `LinearRouter`, this occurs synchronously inside `match` when both label and star flags evaluate to true on a route path. ```typescript } else if (hasLabel && hasStar) { throw new UnsupportedPathError() } ``` Sources: [src/router/linear-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L136-L138) In `PatternRouter`, route compilation is wrapped in a `try...catch` block. If instantiating the dynamic `RegExp` object fails due to invalid regular expression syntax or unsupported token combinations in path segments, the catch block intercepts the error and throws an `UnsupportedPathError`. ```typescript try { this.#routes.push([ new RegExp(`^${parts.join('')}${endsWithWildcard ? '' : '/?$'}`), method, handler, ]) } catch { throw new UnsupportedPathError() } ``` Sources: [src/router/pattern-router/router.ts:33-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L33-L41) | Router Implementation | Error Trigger Location | Failure Condition | Thrown Exception | | :--- | :--- | :--- | :--- | | `LinearRouter` | `match()` method | Route path contains both label (`:`) and wildcard (`*`) | `UnsupportedPathError` | | `PatternRouter` | `add()` method | `new RegExp()` constructor throws on malformed syntax | `UnsupportedPathError` | ```typescript } else if (hasLabel && hasStar) { throw new UnsupportedPathError() } … try { this.#routes.push([ new RegExp(`^${parts.join('')}${endsWithWildcard ? '' : '/?$'}`), method, handler, ]) } catch { throw new UnsupportedPathError() } ``` Sources: [src/router/linear-router/router.ts:136-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts#L136-L138), [src/router/pattern-router/router.ts:33-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts#L33-L41) ## Preset Integration and Size Optimization ### Distribution Entry Points and Preset Routing Hono configures package export maps in `package.json` to expose specialized distribution bundles and entry points, including lightweight presets like `tiny` and `quick`, alongside individual router modules such as `[[LinearRouter]]` and `[[PatternRouter]]`. ```json "./router/linear-router": { "types": "./dist/types/router/linear-router/index.d.ts", "import": "./dist/router/linear-router/index.js", "require": "./dist/cjs/router/linear-router/index.js" }, ``` Sources: [package.json:308-312](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L308-L312) | Export Target Key | Types Definition Path | Import / ESM Path | Require / CJS Path | | :--- | :--- | :--- | :--- | | `./router/linear-router` | `./dist/types/router/linear-router/index.d.ts` | `./dist/router/linear-router/index.js` | `./dist/cjs/router/linear-router/index.js` | | `./router/pattern-router` | `./dist/types/router/pattern-router/index.d.ts` | `./dist/router/pattern-router/index.js` | `./dist/cjs/router/pattern-router/index.js` | | `./router/trie-router` | `./dist/types/router/trie-router/index.d.ts` | `./dist/router/trie-router/index.js` | `./dist/cjs/router/trie-router/index.js` | | `./router/reg-exp-router` | `./dist/types/router/reg-exp-router/index.d.ts` | `./dist/router/reg-exp-router/index.js` | `./dist/cjs/router/reg-exp-router/index.js` | | `./router/smart-router` | `./dist/types/router/smart-router/index.d.ts` | `./dist/router/smart-router/index.js` | `./dist/cjs/router/smart-router/index.js` | ```json "./router/reg-exp-router": { "types": "./dist/types/router/reg-exp-router/index.d.ts", "import": "./dist/router/reg-exp-router/index.js", "require": "./dist/cjs/router/reg-exp-router/index.js" }, "./router/smart-router": { "types": "./dist/types/router/smart-router/index.d.ts", "import": "./dist/router/smart-router/index.js", "require": "./dist/cjs/router/smart-router/index.js" }, "./router/trie-router": { "types": "./dist/types/router/trie-router/index.d.ts", "import": "./dist/router/trie-router/index.js", "require": "./dist/cjs/router/trie-router/index.js" }, "./router/pattern-router": { "types": "./dist/types/router/pattern-router/index.d.ts", "import": "./dist/router/pattern-router/index.js", "require": "./dist/cjs/router/pattern-router/index.js" }, "./router/linear-router": { "types": "./dist/types/router/linear-router/index.d.ts", "import": "./dist/router/linear-router/index.js", "require": "./dist/cjs/router/linear-router/index.js" }, ``` Sources: [package.json:288-312](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L288-L312) ### Type Version Mappings Type definitions for lightweight bundle targets and router exports are mapped explicitly within the `typesVersions` configuration block of `package.json`, ensuring correct TypeScript resolution in size-constrained environments [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds). ```json "tiny": [ "./dist/types/preset/tiny" ], "quick": [ "./dist/types/preset/quick" ], ``` Sources: [package.json:425-430](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L425-L430) ## Related - [Router Contracts](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/routing/router-contracts) - [Presets and Builds](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/presets-and-builds) --- ## Technical docs: Runtime Adapters URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/runtime-adapters
Relevant source files The following files were used as context for generating this wiki page: - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/adapter/cloudflare-workers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/index.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/workerd/index.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/adapter/cloudflare-workers/serve-static-module.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static-module.ts) - [src/adapter/cloudflare-pages/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/conninfo.ts) - [src/adapter/cloudflare-workers/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static.ts) - [src/adapter/netlify/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/index.ts) - [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts) - [src/adapter/bun/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts) - [src/adapter/service-worker/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts) - [src/adapter/bun/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts) - [src/adapter/lambda-edge/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/index.ts) - [src/adapter/deno/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts) - [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts) - [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts) - [src/middleware/context-storage/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts) - [src/adapter/netlify/mod.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/mod.ts) - [src/adapter/cloudflare-workers/utils.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/utils.ts) - [src/adapter/cloudflare-workers/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/conninfo.ts)
## Overview Runtime Adapters bridge Hono's Web Standard-based [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/application-core) and [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) with platform-specific execution environments, request event structures, bindings, and asset-serving facilities. Different serverless, edge, and worker runtimes utilize disparate native entry points, event signatures, and connection metadata mechanisms that diverge from standard `fetch` event flows. Hono's adapter subsystems translate these proprietary structures into clean Web Standard `Request` and `Response` objects, expose secure connection info, and integrate environment bindings seamlessly. Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46) --- ## AWS Lambda Adapters The AWS Lambda-Edge adapter processes CloudFront edge events (`CloudFrontEdgeEvent`) by mapping incoming CloudFront request structures into a Web Standard `Request` object. When an incoming request carries a query string, host header, or body data (including base64-encoded payloads via `decodeBase64`), `createRequest` reconstructs a full URL and populates request headers. Sources: [src/adapter/lambda-edge/handler.ts:116-138](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L116-L138), [src/adapter/lambda-edge/handler.ts:152-184](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L152-L184) The execution flow transforms responses back into CloudFront-compatible formats through `createResult`. If the response content type indicates binary data according to `isContentTypeBinary`, the body is encoded using `encodeBase64` from array buffers, setting `bodyEncoding: 'base64'`. ```typescript export const isContentTypeBinary = (contentType: string): boolean => { return !/^(text\/(plain|html|css|javascript|csv).*|application\/(.*json|.*xml).*|image\/svg\+xml.*)$/.test( contentType ) } ``` Sources: [src/adapter/lambda-edge/handler.ts:140-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L140-L150), [src/adapter/lambda-edge/handler.ts:202-206](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts#L202-L206) --- ## Cloudflare Adapters Cloudflare runtime adapters support both Cloudflare Workers (`workerd`) and Cloudflare Pages. The Cloudflare Workers adapter exposes module-based static asset handling via `getContentFromKVAsset`, WebSocket upgrading through `upgradeWebSocket`, and remote IP retrieval via `getConnInfo`. Static asset request flows are executed through the call chain `module` (in `serve-static-module.ts`) delegating to `serveStatic` (in `serve-static.ts`), which in turn invokes the base `serveStatic` middleware to resolve MIME types and decode URIs. ```mermaid sequenceDiagram participant Mod as module() participant CFSS as serveStatic() participant BaseSS as baseServeStatic() Mod->>CFSS: serveStatic(options) CFSS->>BaseSS: baseServeStatic(options with getContent) BaseSS-->>CFSS: Response / Content CFSS-->>Mod: MiddlewareHandler Response ``` Sources: [src/adapter/cloudflare-workers/serve-static-module.ts:6-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static-module.ts#L6-L10), [src/adapter/cloudflare-workers/serve-static.ts:21-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static.ts#L21-L42), [src/middleware/serve-static/index.ts:35-126](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts#L35-L126) Cloudflare Pages adapters provide `handle` for routing Pages Functions and `handleMiddleware` for executing individual middleware layers against `EventContext`. The `serveStatic` helper inside Cloudflare Pages queries `env.ASSETS.fetch` directly to serve assets from advanced mode configurations. ```typescript export const serveStatic = (): MiddlewareHandler => { return async (c) => { const env = c.env as { ASSETS: FetcherLike } const res = await env.ASSETS.fetch(c.req.raw) if (res.status === 404) { return c.notFound() } return res } } ``` Sources: [src/adapter/cloudflare-pages/handler.ts:32-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L32-L46), [src/adapter/cloudflare-pages/handler.ts:114-123](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L114-L123) --- ## Edge and Serverless Adapters Edge and serverless adapters unify other hosting providers like Vercel, Netlify, and generic Service Workers. The Vercel adapter exports a minimal request handler that forwards incoming requests directly to `app.fetch(req)`. Sources: [src/adapter/vercel/handler.ts:4-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts#L4-L8), [src/adapter/netlify/handler.ts:4-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts#L4-L10) Similarly, the Netlify adapter wraps requests into Hono execution calls with binding contexts. Service worker handlers listen for fetch events (`addEventListener('fetch')`), invoking `app.fetch` with execution contexts and falling back to global fetch operations on 404 statuses if configured. ```typescript export const handle = ( app: Hono, opts: HandleOptions = { fetch: globalThis.fetch.bind(globalThis), } ): Handler => { return (evt) => { evt.respondWith( (async () => { const res = await app.fetch(evt.request, {}, evt) if (opts.fetch && res.status === 404) { return await opts.fetch(evt.request) } return res })() ) } } ``` Sources: [src/adapter/service-worker/handler.ts:18-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts#L18-L36), [src/adapter/service-worker/index.ts:28-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts#L28-L34) --- ## Runtime Detection and Environment Helper The adapter helper module provides runtime detection and environment binding resolution via `getRuntimeKey()` and `env(c)`. `getRuntimeKey()` inspects `navigator.userAgent`, global objects (`EdgeRuntime`, `fastly`), and `process.release.name` to categorize the host engine into a recognized `Runtime` type. | Runtime Key | Detection Condition | Environment Source | | :--- | :--- | :--- | | `deno` | `navigator.userAgent` starts with `'Deno'` | `Deno.env.toObject()` | | `bun` | `navigator.userAgent` starts with `'Bun'` | `globalEnv` (`process.env`) | | `workerd` | `navigator.userAgent` starts with `'Cloudflare-Workers'` | `c.env` | | `node` | `global.process.release.name === 'node'` | `globalEnv` (`process.env`) | | `edge-light` | `typeof global.EdgeRuntime === 'string'` | `globalEnv` (`process.env`) | | `fastly` | `global.fastly !== undefined` | `{}` | | `other` | Fallback when undetected | `{}` | Sources: [src/helper/adapter/index.ts:8-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L8-L41), [src/helper/adapter/index.ts:43-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L43-L84) ## Related - [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving) - [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle) --- ## Technical docs: Bun Adapter URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/bun-adapter
Relevant source files The following files were used as context for generating this wiki page: - [src/adapter/bun/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts) - [src/adapter/bun/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/websocket.ts) - [src/adapter/bun/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts) - [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts) - [src/adapter/cloudflare-workers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/index.ts) - [src/adapter/bun/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/adapter/deno/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts) - [src/adapter/deno/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts) - [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts) - [src/adapter/deno/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts) - [src/adapter/bun/server.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts) - [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts) - [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/helper/websocket/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/websocket/index.ts) - [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts) - [src/adapter/cloudflare-workers/serve-static-module.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static-module.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/adapter/bun/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts) - [src/adapter/service-worker/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts) - [src/adapter/cloudflare-workers/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static.ts)
## Overview The Bun adapter package exposes public barrel exports including `serveStatic`, `bunFileSystemModule`, `toSSG`, `createBunWebSocket`, `upgradeWebSocket`, `websocket`, `getConnInfo`, and `getBunServer`. Sources: [src/adapter/bun/index.ts:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts#L1-L11) The adapter retrieves the running Bun server instance from [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) via `getBunServer`, accessing underlying request IP functions and WebSocket server upgrade capabilities. Sources: [src/adapter/bun/server.ts:1-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts#L1-L14), [src/adapter/bun/websocket.ts:48-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/websocket.ts#L48-L72), [src/adapter/bun/conninfo.ts:10-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L10-L28) Static asset middleware integrates with [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving) through `Bun.file` and Node.js filesystem helpers to check paths, determine directories, and serve content. Sources: [src/adapter/bun/serve-static.ts:1-31](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts#L1-L31) Connection metadata extraction parses server remote address and socket details into standardized IP structures using Bun's `requestIP` API. Sources: [src/adapter/bun/conninfo.ts:10-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L10-L43) [Static site generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation) is supported via experimental filesystem bindings and `toSSG` adapters that interface directly with Bun's native write methods. Sources: [src/adapter/bun/ssg.ts:1-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L1-L27) ## Entry point and module exports ### Public Module Surface The Bun adapter package exports functions, modules, and type definitions that bridge Hono with the Bun runtime environment. These modules include static asset serving, SSG integration, WebSocket management, connection information extraction, and server instance retrieval. Sources: [src/adapter/bun/index.ts:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts#L1-L11) | Export Symbol | Export Type | Source Module | Purpose | | --- | --- | --- | --- | | `serveStatic` | Function | `./serve-static` | Serves static assets using Bun file system APIs | | `bunFileSystemModule` | Object | `./ssg` | Provides filesystem bindings for static site generation | | `toSSG` | Function | `./ssg` | Generates static site outputs via Bun filesystem integration | | `createBunWebSocket` | Function | `./websocket` | Creates a Bun-specific WebSocket handler and upgrade pair | | `upgradeWebSocket` | Function | `./websocket` | Upgrades HTTP requests to WebSockets on Bun | | `websocket` | Object | `./websocket` | WebSocket configuration helper object | | `BunWebSocketData` | Type | `./websocket` | Type definition for Bun WebSocket state data | | `BunWebSocketHandler` | Type | `./websocket` | Type definition for Bun WebSocket event handlers | | `getConnInfo` | Function | `./conninfo` | Extracts remote connection metadata from requests | | `getBunServer` | Function | `./server` | Retrieves the running Bun server instance from execution context | Sources: [src/adapter/bun/index.ts:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts#L1-L11) > [!NOTE] > All exports from `src/adapter/bun/index.ts` are re-exported at the package root to provide direct access to Bun-specific features without deep import paths. > Sources: [src/adapter/bun/index.ts:1-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts#L1-L11) ## Native Bun server reference management ### Server Retrieval via getBunServer The `getBunServer` helper function extracts the active Bun server instance from an [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) `Context` object. It accepts a generic type parameter `T` representing the specific Bun server type and inspects the context environment bindings (`c.env`) to locate the server reference. Sources: [src/adapter/bun/server.ts:1-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts#L1-L14) ```typescript export const getBunServer = (c: Context): T | undefined => ('server' in c.env ? c.env.server : c.env) as T | undefined ``` Sources: [src/adapter/bun/server.ts:1-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts#L1-L14) > [!NOTE] > The function checks whether the `server` property exists directly on `c.env`. If present, it returns `c.env.server`; otherwise, it falls back to treating `c.env` itself as the server instance, casting the result to type `T | undefined`. > Sources: [src/adapter/bun/server.ts:13-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts#L13-L14) ## Static asset resolution via Bun.file ### Middleware Integration and Native Handlers The Bun adapter provides a specialized `serveStatic` middleware function that wraps Hono's base static asset handler (`baseServeStatic`) from [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving). It injects Bun-specific file system primitives (`Bun.file`) and Node.js `fs/promises` utilities to resolve file existence, query directory status, and join paths. Sources: [src/adapter/bun/serve-static.ts:1-31](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts#L1-L31) ```typescript export const serveStatic = ( options: ServeStaticOptions = {} ): MiddlewareHandler => { return async function serveStatic(c, next) { const getContent = async (path: string) => { // @ts-ignore const file = Bun.file(path) return (await file.exists()) ? file : null } const isDir = async (path: string) => { let isDir try { const stats = await stat(path) isDir = stats.isDirectory() } catch {} return isDir } return baseServeStatic({ ...options, getContent, join, isDir, })(c, next) } } ``` Sources: [src/adapter/bun/serve-static.ts:8-31](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts#L8-L31) > [!NOTE] > The `getContent` closure calls `Bun.file(path)` and evaluates `file.exists()`, returning the Bun file handle if present or `null` otherwise. Directory checking (`isDir`) uses `node:fs/promises` `stat` wrapped in a try/catch block to safely handle missing paths without throwing unhandled exceptions. > Sources: [src/adapter/bun/serve-static.ts:12-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts#L12-L24) ## Connection info extraction ### Server Request Metadata and Remote Address Mapping The Bun adapter implements connection metadata extraction through the `getConnInfo` function, which conforms to the `GetConnInfo` helper signature. It retrieves the underlying Bun server instance via `getBunServer` with typed constraints for `requestIP`, ensuring that runtime execution environments supply the required second argument to `fetch`. Sources: [src/adapter/bun/conninfo.ts:10-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L10-L42) ```typescript export const getConnInfo: GetConnInfo = (c: Context) => { const server = getBunServer<{ requestIP?: (req: Request) => { address: string family: string port: number } | null }>(c) if (!server) { throw new TypeError('env has to include the 2nd argument of fetch.') } if (typeof server.requestIP !== 'function') { throw new TypeError('server.requestIP is not a function.') } // https://bun.sh/docs/runtime/http/server#server-requestip-request // Returns null for closed requests or Unix domain sockets. const info = server.requestIP(c.req.raw) if (!info) { return { remote: {}, } } return { remote: { address: info.address, addressType: info.family === 'IPv6' || info.family === 'IPv4' ? info.family : undefined, port: info.port, }, } ``` Sources: [src/adapter/bun/conninfo.ts:10-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L10-L42) > [!WARNING] > If `c.env` lacks a server reference or `server.requestIP` is not a function, `getConnInfo` throws a `TypeError`. This occurs when requests are processed without binding the Bun server instance to the execution context. > Sources: [src/adapter/bun/conninfo.ts:19-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L19-L24) ### Socket Family Validation and Fallback Handling The function invokes `server.requestIP(c.req.raw)` to query client connection properties. When operating over Unix domain sockets or processing closed requests, `requestIP` returns `null`, causing `getConnInfo` to return an empty remote object `{ remote: {} }`. Sources: [src/adapter/bun/conninfo.ts:28-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L28-L34) When valid socket information is returned, the adapter maps the properties to a standardized structure. The `addressType` field explicitly validates that the family string equals `'IPv6'` or `'IPv4'`, assigning `undefined` for any unrecognized socket family. Sources: [src/adapter/bun/conninfo.ts:36-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L36-L42) ## Static site generation support ### Filesystem Modules and SSG Integration The Bun adapter provides experimental static site generation bindings that bridge Hono's base SSG helper with Bun's high-performance file system APIs. The `bunFileSystemModule` defines a custom `FileSystemModule` interface implementation using Bun's native `write` method for writing build outputs. Sources: [src/adapter/bun/ssg.ts:1-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L1-L19) ```typescript /* eslint-disable @typescript-eslint/ban-ts-comment */ import { toSSG as baseToSSG } from '../../helper/ssg' import type { FileSystemModule, ToSSGAdaptorInterface } from '../../helper/ssg' // @ts-ignore const { write } = Bun /** * @experimental * `bunFileSystemModule` is an experimental feature. * The API might be changed. */ export const bunFileSystemModule: FileSystemModule = { writeFile: async (path, data) => { await write(path, data) }, mkdir: async () => {}, } ``` Sources: [src/adapter/bun/ssg.ts:1-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L1-L19) > [!WARNING] > Both `bunFileSystemModule` and the `toSSG` adaptor function are marked as experimental. Their underlying APIs are subject to change in future releases. > Sources: [src/adapter/bun/ssg.ts:8-12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L8-L12), [src/adapter/bun/ssg.ts:20-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L20-L24) ### SSG Adapter Interface Execution The adapter exports a `toSSG` function matching the `ToSSGAdaptorInterface` signature. It delegates execution to the core `baseToSSG` helper, passing the application instance, the Bun-specific filesystem module, and user-provided generation options. Sources: [src/adapter/bun/ssg.ts:20-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L20-L27) ```typescript /** * @experimental * `toSSG` is an experimental feature. * The API might be changed. */ export const toSSG: ToSSGAdaptorInterface = async (app, options) => { return baseToSSG(app, bunFileSystemModule, options) } ``` Sources: [src/adapter/bun/ssg.ts:20-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/ssg.ts#L20-L27) ## Related - [WebSocket Support](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/websocket-support) - [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving) --- ## Technical docs: Deno Adapter URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/deno-adapter
Relevant source files The following files were used as context for generating this wiki page: - [src/adapter/deno/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts) - [src/adapter/deno/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts) - [src/adapter/deno/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/adapter/deno/deno.d.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/deno.d.ts) - [src/adapter/bun/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/index.ts) - [src/adapter/cloudflare-workers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/index.ts) - [src/adapter/deno/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/adapter/bun/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/websocket.ts) - [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts) - [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts) - [src/adapter/service-worker/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/index.ts) - [src/adapter/cloudflare-pages/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/index.ts) - [src/hono.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/adapter/deno/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts) - [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts) - [src/adapter/bun/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/serve-static.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts) - [src/adapter/vercel/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/handler.ts) - [src/adapter/service-worker/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/service-worker/handler.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/helper/websocket/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/websocket/index.ts) - [src/adapter/vercel/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/index.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts)
## Overview The Deno Adapter provides runtime integration for running Hono applications within the Deno environment. It bridges Hono's middleware and helper systems with Deno-specific platform APIs, exposing modules for [static file serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving), WebSocket upgrading, [static site generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation), and connection network metadata extraction. Sources: [src/adapter/deno/index.ts:1-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts#L1-L9) ## Module exports and entry points ### Public API Surface The `hono/deno` entry point exposes specific utility modules designed for the Deno runtime environment. These exports bridge standard Hono mechanics with Deno platform features such as file system-based static asset delivery, static site generation module bindings, WebSocket connection upgrades, and remote connection metadata retrieval. | Export Name | Source Module | Purpose | | --- | --- | --- | | `serveStatic` | `./serve-static` | Serves static files from the Deno file system [Static Site Generation](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-site-generation) | | `toSSG` | `./ssg` | Generates static sites using Deno file system bindings | | `denoFileSystemModule` | `./ssg` | Provides Deno file system methods for static site generation output | | `upgradeWebSocket` | `./websocket` | Upgrades standard HTTP connections to Deno WebSocket streams | | `getConnInfo` | `./conninfo` | Extracts remote client network metadata from Deno incoming connections | Sources: [src/adapter/deno/index.ts:1-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/index.ts#L1-L9) ### Runtime Environment Detection The adapter helper module defines the runtime identifier `'deno'` alongside other supported execution engines. When evaluating runtime environments through `getRuntimeKey`, the Deno runtime is identified by matching the `navigator.userAgent` string against known user agent configurations. | Runtime Key | User Agent String / Detection Criteria | | --- | --- | | `deno` | `Deno` | | `bun` | `Bun` | | `workerd` | `Cloudflare-Workers` | | `node` | `Node.js` | | `edge-light` | `global.EdgeRuntime` string presence | | `fastly` | `global.fastly` definition check | | `other` | Fallback when no specific runtime matches | Sources: [src/helper/adapter/index.ts:43-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L43-L84) > [!NOTE] > Environment variable resolution in the adapter helper accesses `Deno.env.toObject()` when the runtime key resolves to `'deno'`, mapping runtime configuration directly into typed bindings. Sources: [src/helper/adapter/index.ts:29-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts#L29-L33) ## Serving static files from disk ### File System Adapter Integration The `serveStatic` helper in `src/adapter/deno/serve-static.ts` wraps Hono's core `baseServeStatic` middleware from `src/middleware/serve-static` to deliver assets directly from the Deno file system. It destructs `open`, `lstatSync`, and `errors` from the global `Deno` namespace to handle file resolution and directory checks. ```typescript const { open, lstatSync, errors } = Deno export const serveStatic = ( options: ServeStaticOptions = {} ): MiddlewareHandler => { return async function serveStatic(c, next) { const getContent = async (path: string) => { try { if (isDir(path)) { return null } const file = await open(path) return file.readable } catch (e) { if (!(e instanceof errors.NotFound)) { console.warn(`${e}`) } return null } } const isDir = (path: string) => { let isDir try { const stat = lstatSync(path) isDir = stat.isDirectory } catch {} return isDir } return baseServeStatic({ ...options, getContent, join, isDir, })(c, next) } } ``` Sources: [src/adapter/deno/serve-static.ts:6-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts#L6-L42) ### Asset Resolution and Error Handling When a request arrives, `getContent` first checks whether the target path points to a directory using the internal `isDir` helper backed by `Deno.lstatSync`. If the path represents a directory, `getContent` returns `null` immediately to trigger directory index fallback or routing continuation. Otherwise, it attempts to open the file via `Deno.open` and returns its `.readable` stream property. ```typescript const getContent = async (path: string) => { try { if (isDir(path)) { return null } const file = await open(path) return file.readable } catch (e) { if (!(e instanceof errors.NotFound)) { console.warn(`${e}`) } return null } } const isDir = (path: string) => { let isDir try { const stat = lstatSync(path) isDir = stat.isDirectory } catch {} return isDir } ``` Sources: [src/adapter/deno/serve-static.ts:12-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts#L12-L34) > [!WARNING] > Any caught exception during file opening that is not an instance of `Deno.errors.NotFound` is logged via `console.warn`, whereas `NotFound` errors are silently ignored to allow clean fallback handling by downstream middleware. Sources: [src/adapter/deno/serve-static.ts:20-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/serve-static.ts#L20-L25) ## WebSocket upgrade integration ### Upgrade Mechanism and Subprotocol Negotiation The `upgradeWebSocket` helper wraps Hono's `defineWebSocketHelper` to handle full-duplex WebSocket connections in Deno. It first inspects the incoming request headers; if the `upgrade` header does not equal `'websocket'`, the helper returns `undefined` to let standard HTTP request handling proceed. ```typescript export const upgradeWebSocket: UpgradeWebSocket = defineWebSocketHelper(async (c, events, options) => { if (c.req.header('upgrade') !== 'websocket') { return } ``` Sources: [src/adapter/deno/websocket.ts:4-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts#L4-L9) To ensure browser compatibility, the helper extracts the first requested subprotocol from the `sec-websocket-protocol` header. Echoing this subprotocol back prevents connection rejections in strict clients such as Google Chrome when subprotocols are negotiated. ```typescript // Echo the negotiated subprotocol back to the client. Browsers (e.g. Chrome) // reject the connection when a subprotocol was requested but the response is // missing the `Sec-WebSocket-Protocol` header. const subprotocol = c.req.header('sec-websocket-protocol')?.split(',')[0]?.trim() const { response, socket } = Deno.upgradeWebSocket(c.req.raw, { ...(subprotocol ? { protocol: subprotocol } : {}), ...options, }) ``` Sources: [src/adapter/deno/websocket.ts:10-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts#L10-L18) > [!NOTE] > The `Deno.upgradeWebSocket` function accepts `req` along with `UpgradeWebSocketOptions`, returning an object containing both the HTTP `response` and the underlying `socket`. Sources: [src/adapter/deno/websocket.ts:15-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts#L15-L18), [src/adapter/deno/deno.d.ts:49-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/deno.d.ts#L49-L55) ### WSContext Event Bridging Once the native socket is established, `upgradeWebSocket` instantiates a `WSContext` wrapper that maps property getters and methods onto the Deno socket. It wires event handlers `onopen`, `onmessage`, `onclose`, and `onerror` directly to the corresponding callbacks defined in the event parameter object. ```typescript const wsContext: WSContext = new WSContext({ close: (code, reason) => socket.close(code, reason), get protocol() { return socket.protocol }, raw: socket, get readyState() { return socket.readyState as WSReadyState }, url: socket.url ? new URL(socket.url) : null, send: (source) => socket.send(source), }) socket.onopen = (evt) => events.onOpen?.(evt, wsContext) socket.onmessage = (evt) => events.onMessage?.(evt, wsContext) socket.onclose = (evt) => events.onClose?.(evt, wsContext) socket.onerror = (evt) => events.onError?.(evt, wsContext) return response ``` Sources: [src/adapter/deno/websocket.ts:20-37](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts#L20-L37) The configuration options accepted by Deno's WebSocket upgrade routine are typed through `Deno.UpgradeWebSocketOptions`, supporting protocol selection and idle timeout configuration. | Option | Type | Default | Purpose | | --- | --- | --- | --- | | `protocol` | `string` | — | Sets the `.protocol` property on the client-side WebSocket to match requested subprotocols | | `idleTimeout` | `number` | `30` | Maximum seconds without a pong frame before connection is deemed unhealthy and closed; set to `0` to disable | Sources: [src/adapter/deno/deno.d.ts:60-78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/deno.d.ts#L60-L78) ## Extracting connection network metadata ### Connection Info Helper Signature and Environment Binding The `getConnInfo` helper extracts remote client connection metadata from the [execution context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) in Deno environments. It conforms to the `GetConnInfo` type definition and reads `remoteAddr` directly from the environment bindings property `c.env`. ```typescript import type { GetConnInfo } from '../../helper/conninfo' /** * Get conninfo with Deno * @param c Context * @returns ConnInfo */ export const getConnInfo: GetConnInfo = (c) => { const { remoteAddr } = c.env return { remote: { address: remoteAddr.hostname, port: remoteAddr.port, transport: remoteAddr.transport, }, } ``` Sources: [src/adapter/deno/conninfo.ts:1-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts#L1-L16) ### Remote Address Mapping The function returns a structured `ConnInfo` object containing a nested `remote` object. It maps property values from the Deno `remoteAddr` instance to standard address fields. | Field | Source Property | Type / Description | | --- | --- | --- | | `address` | `remoteAddr.hostname` | Remote IP address or hostname of the connected client | | `port` | `remoteAddr.port` | Network port number used by the client connection | | `transport` | `remoteAddr.transport` | Underlying transport protocol (`tcp` or `udp`) | Sources: [src/adapter/deno/conninfo.ts:8-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts#L8-L16) > [!NOTE] > `getConnInfo` assumes that `c.env` provides a populated `remoteAddr` object with `hostname`, `port`, and `transport` properties matching Deno's network address structure. Sources: [src/adapter/deno/conninfo.ts:8-15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts#L8-L15) ## Static site generation with Deno ### File System Module Integration The `hono/deno` adapter integrates with static site generation by wiring Deno native file system APIs into Hono's core SSG framework. The `denoFileSystemModule` object satisfies the `FileSystemModule` interface by implementing file writing and directory creation primitives. ```typescript export const denoFileSystemModule: FileSystemModule = { writeFile: async (path, data) => { const uint8Data = typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data) await Deno.writeFile(path, uint8Data) }, mkdir: async (path, options) => { return Deno.mkdir(path, { recursive: options?.recursive ?? false }) }, } ``` Sources: [src/adapter/deno/ssg.ts:9-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L9-L18) When `writeFile` is invoked, it checks whether the provided data is a string; if so, it encodes the text into a `Uint8Array` using `TextEncoder`, otherwise it wraps or casts the input data as a `Uint8Array` before calling `Deno.writeFile`. The `mkdir` method forwards directory creation requests to `Deno.mkdir`, defaulting the recursive flag to `false` if options are omitted. ```typescript writeFile: async (path, data) => { const uint8Data = typeof data === 'string' ? new TextEncoder().encode(data) : new Uint8Array(data) await Deno.writeFile(path, uint8Data) }, mkdir: async (path, options) => { return Deno.mkdir(path, { recursive: options?.recursive ?? false }) }, ``` Sources: [src/adapter/deno/ssg.ts:10-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L10-L17) > [!NOTE] > Both `denoFileSystemModule` and the `toSSG` export are marked as experimental features whose APIs may change in future releases. Sources: [src/adapter/deno/ssg.ts:4-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L4-L8), [src/adapter/deno/ssg.ts:20-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L20-L24) ### SSG Execution Function The `toSSG` adapter function matches the `ToSSGAdaptorInterface` signature, taking a Hono application instance and generation options, and delegating execution to the base `toSSG` utility bundled with `denoFileSystemModule`. ```typescript export const toSSG: ToSSGAdaptorInterface = async (app, options) => { return baseToSSG(app, denoFileSystemModule, options) } ``` Sources: [src/adapter/deno/ssg.ts:25-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/ssg.ts#L25-L27) ## Related - [WebSocket Support](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/websocket-support) - [Static File Serving](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/static-file-serving) --- ## Technical docs: JWT and JWK URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/jwt-and-jwk
Relevant source files The following files were used as context for generating this wiki page: - [src/utils/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts) - [src/utils/jwt/jws.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts) - [src/middleware/jwk/jwk.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts) - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/middleware/jwk/keys.test.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/keys.test.json) - [src/middleware/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts) - [src/middleware/bearer-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/middleware/basic-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts) - [src/middleware/csrf/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts) - [src/middleware/etag/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/helper/cookie/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/cookie/index.ts) - [src/utils/jwt/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/middleware/jwk/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/index.ts) - [src/utils/crypto.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/crypto.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/utils/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/index.ts) - [src/client/fetch-result-please.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/client/fetch-result-please.ts) - [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/utils/cookie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/cookie.ts) - [src/utils/jwt/jwa.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwa.ts) - [src/utils/jwt/utf8.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/utf8.ts) - [jsr.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/jsr.json) - [src/router/linear-router/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/index.ts) - [src/helper/accepts/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/index.ts)
## Overview Hono provides native JSON Web Token (JWT) and JSON Web Key (JWK) utilities alongside dedicated middleware handlers to authenticate HTTP requests securely across Web Standard runtimes. By leveraging `crypto.subtle`, the implementation handles cryptographic signing, signature verification, and dynamic key resolution without external cryptographic dependencies. Sources: [src/utils/jwt/jwt.ts:1-29](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L1-L29), [src/utils/jwt/jws.ts:1-12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L1-L12), [src/middleware/jwt/jwt.ts:1-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L1-L20), [src/middleware/jwk/jwk.ts:1-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts#L1-L16) ## Token Signing and Key Resolution ### Signing Workflow and Serialisation Token generation begins by serialising the payload and header objects into Base64Url-encoded strings without padding. The `sign` function first encodes the `JWTPayload` object using `encodeJwtPart`, which converts the JSON-serialised payload into UTF-8 bytes and transforms it via `encodeBase64Url`, stripping any trailing `=` characters. ```typescript const encodeJwtPart = (part: unknown): string => encodeBase64Url(utf8Encoder.encode(JSON.stringify(part)).buffer).replace(/=/g, '') const encodeSignaturePart = (buf: ArrayBufferLike): string => encodeBase64Url(buf).replace(/=/g, '') ``` Sources: [src/utils/jwt/jwt.ts:31-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L31-L34) Next, the header is constructed. If the supplied `privateKey` is an object containing an `alg` property, the algorithm and optional `kid` (Key ID) are extracted into the header. Otherwise, the provided algorithm parameter (defaulting to `'HS256'`) is used alongside `typ: 'JWT'`. The header and payload are concatenated with a dot delimiter (`${encodedHeader}.${encodedPayload}`) to form the partial token. ```typescript export const sign = async ( payload: JWTPayload, privateKey: SignatureKey, alg: SignatureAlgorithm = 'HS256' ): Promise => { const encodedPayload = encodeJwtPart(payload) let encodedHeader if (typeof privateKey === 'object' && 'alg' in privateKey) { alg = privateKey.alg as SignatureAlgorithm encodedHeader = encodeJwtPart({ alg, typ: 'JWT', kid: privateKey.kid }) } else { encodedHeader = encodeJwtPart({ alg, typ: 'JWT' }) } const partialToken = `${encodedHeader}.${encodedPayload}` const signaturePart = await signing(privateKey, alg, utf8Encoder.encode(partialToken)) const signature = encodeSignaturePart(signaturePart) return `${partialToken}.${signature}` } ``` Sources: [src/utils/jwt/jwt.ts:56-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L56-L76) ### Call-Chain Execution Walkthrough When `sign` invokes the signing routine, execution flows through the JWS and Web Crypto resolution layers. 1. `sign` in `src/utils/jwt/jwt.ts` invokes `signing` with the private key, algorithm identifier, and encoded partial token bytes. 2. `signing` in `src/utils/jwt/jws.ts` calls `getKeyAlgorithm(alg)` to map the string algorithm to a Web Crypto `KeyAlgorithm` parameter structure. 3. `getKeyAlgorithm` inspects the algorithm name; if an unsupported identifier is supplied, it falls through or throws `JwtAlgorithmNotImplemented`. 4. `signing` then calls `importPrivateKey(privateKey, algorithm)` to prepare the cryptographic key instance. 5. `crypto.subtle.sign` executes against the imported `CryptoKey` to produce the raw signature buffer, which is subsequently encoded and appended to the token string. ```mermaid sequenceDiagram participant jwt.ts participant jws.ts participant jwa.ts participant types.ts jwt.ts->>jws.ts: signing(privateKey, alg, data) jws.ts->>jws.ts: getKeyAlgorithm(alg) alt algorithm unsupported jwa.ts-->>types.ts: JwtAlgorithmNotImplemented end jws.ts->>jws.ts: importPrivateKey(privateKey, algorithm) jws.ts->>crypto.subtle: sign(algorithm, cryptoKey, data) crypto.subtle-->>jws.ts: ArrayBuffer signature jws.ts-->>jwt.ts: raw signature buffer ``` Sources: [src/utils/jwt/jwt.ts:72-72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L72-L72), [src/utils/jwt/jws.ts:29-37](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L29-L37), [src/utils/jwt/jws.ts:122-179](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L122-L179), [src/utils/jwt/types.ts:6-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts#L6-L11) ### Web Crypto Key Resolution The `importPrivateKey` function handles diverse key representations, including raw strings, PEM-encoded structures, JWK objects, and existing `CryptoKey` instances. It ensures that the resulting key is assigned the `CryptoKeyUsage.Sign` usage flag. ```typescript async function importPrivateKey(key: SignatureKey, alg: KeyImporterAlgorithm): Promise { if (!crypto.subtle || !crypto.subtle.importKey) { throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.') } if (isCryptoKey(key)) { if (key.type !== 'private' && key.type !== 'secret') { throw new Error( `unexpected key type: CryptoKey.type is ${key.type}, expected private or secret` ) } return key } const usages = [CryptoKeyUsage.Sign] if (typeof key === 'object') { return await crypto.subtle.importKey('jwk', key, alg, false, usages) } if (key.includes('PRIVATE')) { return await crypto.subtle.importKey('pkcs8', pemToBinary(key), alg, false, usages) } return await crypto.subtle.importKey('raw', utf8Encoder.encode(key), alg, false, usages) } ``` Sources: [src/utils/jwt/jws.ts:54-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L54-L76) > [!WARNING] > When passing an existing `CryptoKey` to `importPrivateKey`, its `type` property must be either `'private'` or `'secret'`. Passing a public key where a private or secret key is required causes an immediate error. Sources: [src/utils/jwt/jws.ts:58-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L58-L64) ## Token Verification and Claims Validation ### Claims Verification Options Token validation begins with structural decoding and signature verification, separating cryptographic checks from payload claims assertions. The `decode` function splits the token by periods, verifying that exactly three parts exist before parsing the header and payload components. Sources: [src/utils/jwt/jwt.ts:264-279](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L264-L279) ```typescript export const decode = (token: string): { header: TokenHeader; payload: JWTPayload } => { const parts = token.split('.') if (parts.length !== 3) { throw new JwtTokenInvalid(token) } try { const header = decodeJwtPart(parts[0]) as TokenHeader const payload = decodeJwtPart(parts[1]) as JWTPayload return { header, payload, } } catch { throw new JwtTokenInvalid(token) } } ``` Sources: [src/utils/jwt/jwt.ts:264-279](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L264-L279) The `VerifyOptions` type configures how standard registered claims are validated against the current system time and expected constraints during token verification. Sources: [src/utils/jwt/jwt.ts:78-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L78-L94) | Option | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `iss` | `string \| RegExp` | — | Expected issuer used for verifying the `iss` claim | | `nbf` | `boolean` | `true` | Verify that the current timestamp is after or equal to the `nbf` claim | | `exp` | `boolean` | `true` | Verify that the current timestamp is before the `exp` claim | | `iat` | `boolean` | `true` | Verify that the `iat` claim is a valid number not in the future | | `aud` | `string \| string[] \| RegExp` | — | Expected audience used for verifying the `aud` claim | | `alg` | `SignatureAlgorithm` | — | Required signature algorithm for verification | Sources: [src/utils/jwt/jwt.ts:78-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L78-L94) > [!NOTE] > If the `alg` option is omitted during verification, the verifier immediately throws a `JwtAlgorithmRequired` error to prevent algorithm substitution vulnerabilities. Sources: [src/utils/jwt/jwt.ts:99-101](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L99-L101) ## JSON Web Key Set Middleware ### JWKS Retrieval and Key Matching The `verifyWithJwks` function retrieves and validates JSON Web Key Sets (JWKS) to verify incoming tokens without pre-configured static keys. It first decodes the token header and checks for a valid header structure and a mandatory `kid` (Key ID) property. If the header lacks a `kid`, `JwtHeaderRequiresKid` is thrown. Sources: [src/utils/jwt/jwt.ts:209-216](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L209-L216) ```typescript export const verifyWithJwks = async ( token: string, options: { keys?: HonoJsonWebKey[] jwks_uri?: string verification?: VerifyOptions allowedAlgorithms: readonly AsymmetricAlgorithm[] }, init?: RequestInit ): Promise => { const verifyOpts = options.verification || {} const header = decodeHeader(token) if (!isTokenHeader(header)) { throw new JwtHeaderInvalid(header) } if (!header.kid) { throw new JwtHeaderRequiresKid(header) } ``` Sources: [src/utils/jwt/jwt.ts:197-216](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L197-L216) > [!WARNING] > Symmetric algorithms such as `HS256`, `HS384`, and `HS512` are explicitly prohibited during JWKS verification. Any token header using a symmetric algorithm causes `verifyWithJwks` to throw a `JwtSymmetricAlgorithmNotAllowed` error to prevent algorithm confusion attacks. Sources: [src/utils/jwt/jwt.ts:190-221](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L190-L221) ```typescript // Reject symmetric algorithms (HS256, HS384, HS512) to prevent algorithm confusion attacks if (symmetricAlgorithms.includes(header.alg as SymmetricAlgorithm)) { throw new JwtSymmetricAlgorithmNotAllowed(header.alg) } // Validate against allowed algorithms if (!options.allowedAlgorithms.includes(header.alg as AsymmetricAlgorithm)) { throw new JwtAlgorithmNotAllowed(header.alg, options.allowedAlgorithms) } ``` Sources: [src/utils/jwt/jwt.ts:218-226](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L218-L226) When an `options.jwks_uri` is supplied, `verifyWithJwks` fetches the URI using the optional `RequestInit` init argument, parses the JSON response, and ensures that a `keys` array exists. These fetched keys are merged with any statically provided `options.keys`. The verifier then finds the specific key where `key.kid === header.kid`. Sources: [src/utils/jwt/jwt.ts:228-251](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L228-L251) ```typescript let verifyKeys = options.keys ? [...options.keys] : undefined if (options.jwks_uri) { const response = await fetch(options.jwks_uri, init) if (!response.ok) { throw new Error(`failed to fetch JWKS from ${options.jwks_uri}`) } const data = (await response.json()) as { keys?: JsonWebKey[] } if (!data.keys) { throw new Error('invalid JWKS response. "keys" field is missing') } if (!Array.isArray(data.keys)) { throw new Error('invalid JWKS response. "keys" field is not an array') } verifyKeys ??= [] verifyKeys.push(...(data.keys as HonoJsonWebKey[])) } else if (!verifyKeys) { throw new Error('verifyWithJwks requires options for either "keys" or "jwks_uri" or both') } const matchingKey = verifyKeys.find((key) => key.kid === header.kid) if (!matchingKey) { throw new JwtTokenInvalid(token) } // Verify that JWK's alg matches JWT header's alg when JWK has alg field if (matchingKey.alg && matchingKey.alg !== header.alg) { throw new JwtAlgorithmMismatch(matchingKey.alg, header.alg) } return await verify(token, matchingKey, { alg: header.alg, ...verifyOpts, }) } ``` Sources: [src/utils/jwt/jwt.ts:228-262](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L228-L262) ### Verification Execution and Call Chain The execution flow for JWKS-based verification proceeds through structural header inspection and key resolution. 1. `verifyWithJwks` — Entry point for verifying tokens against local keys or a remote JWKS endpoint. Sources: [src/utils/jwt/jwt.ts:197-210](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L197-L210) 2. `decodeHeader` — Splits the token by periods and decodes the first segment into a `TokenHeader` object. Sources: [src/utils/jwt/jwt.ts:281-290](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L281-L290) 3. `JwtTokenInvalid` — Thrown if the token does not contain exactly three parts or if part decoding fails. Sources: [src/utils/jwt/jwt.ts:265-268](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L265-L268), [src/utils/jwt/jwt.ts:283-289](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L283-L289) ```mermaid sequenceDiagram participant verifyWithJwks as src/utils/jwt/jwt.ts participant decodeHeader as src/utils/jwt/jwt.ts participant JwtTokenInvalid as src/utils/jwt/types.ts verifyWithJwks->>decodeHeader: decodeHeader(token) decodeHeader->>JwtTokenInvalid: throw JwtTokenInvalid(token) if parts length !== 3 ``` Sources: [src/utils/jwt/jwt.ts:209-210](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L209-L210), [src/utils/jwt/jwt.ts:281-290](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L281-L290) > [!NOTE] > If a matching JWK defines an explicit `alg` property, it must strictly match the `alg` declared in the JWT header. A mismatch causes a `JwtAlgorithmMismatch` exception. Sources: [src/utils/jwt/jwt.ts:253-256](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts#L253-L256) ## JWT Authentication Middleware Flow ### Credential Extraction and Token Resolution The `jwt` middleware intercepts incoming HTTP requests to locate and validate JSON Web Tokens from configured request headers or cookies. It first checks the request headers using `options.headerName` (defaulting to `'Authorization'`). When credentials are found in the header, the middleware splits the string by whitespace and expects exactly two parts where the first segment case-insensitively equals `'bearer'`. If the credential structure is invalid, it throws an `HTTPException` with status code `401`. Sources: [src/middleware/jwt/jwt.ts:76-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L76-L95) ```typescript return async function jwt(ctx, next) { const headerName = options.headerName || 'Authorization' const credentials = ctx.req.raw.headers.get(headerName) let token if (credentials) { const parts = credentials.split(/\s+/) if (parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') { const errDescription = 'invalid credentials structure' throw new HTTPException(401, { message: errDescription, res: unauthorizedResponse({ ctx, error: 'invalid_request', errDescription, }), }) } else { token = parts[1] } ``` Sources: [src/middleware/jwt/jwt.ts:76-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L76-L95) If no header credentials exist, the middleware evaluates `options.cookie`. The `cookie` option can be provided as a plain string key or an object containing `key`, an optional `secret` for signed cookies, and optional `prefixOptions`. Depending on these options, the token is extracted using `getCookie` or `getSignedCookie`. Sources: [src/middleware/jwt/jwt.ts:96-117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L96-L117) ```typescript } else if (options.cookie) { if (typeof options.cookie == 'string') { token = getCookie(ctx, options.cookie) } else if (options.cookie.secret) { if (options.cookie.prefixOptions) { token = await getSignedCookie( ctx, options.cookie.secret, options.cookie.key, options.cookie.prefixOptions ) } else { token = await getSignedCookie(ctx, options.cookie.secret, options.cookie.key) } } else { if (options.cookie.prefixOptions) { token = getCookie(ctx, options.cookie.key, options.cookie.prefixOptions) } else { token = getCookie(ctx, options.cookie.key) } } } ``` Sources: [src/middleware/jwt/jwt.ts:96-117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L96-L117) > [!WARNING] > If neither header credentials nor a valid cookie yields a token string, the middleware immediately rejects the request with a `401` HTTP exception and an `invalid_request` error description. Sources: [src/middleware/jwt/jwt.ts:119-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L119-L129) ```typescript if (!token) { const errDescription = 'no authorization included in request' throw new HTTPException(401, { message: errDescription, res: unauthorizedResponse({ ctx, error: 'invalid_request', errDescription, }), }) } ``` Sources: [src/middleware/jwt/jwt.ts:119-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L119-L129) ### Verification, Context Injection, and 401 Responses Once a token is extracted, the middleware invokes `Jwt.verify` with the configured `secret`, `alg`, and verification options. If verification fails or throws an error, a `401` exception is raised with an `invalid_token` error and a `WWW-Authenticate` challenge header. Upon successful verification, the decoded payload is stored in the [execution context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) under the key `'jwtPayload'`, and control proceeds to the next handler via `await next()`. Sources: [src/middleware/jwt/jwt.ts:131-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L131-L157) ```typescript let payload let cause try { payload = await Jwt.verify(token, options.secret, { alg: options.alg, ...verifyOpts, }) } catch (e) { cause = e } if (!payload) { throw new HTTPException(401, { message: 'Unauthorized', res: unauthorizedResponse({ ctx, error: 'invalid_token', statusText: 'Unauthorized', errDescription: 'token verification failure', }), cause, }) } ctx.set('jwtPayload', payload) await next() } ``` Sources: [src/middleware/jwt/jwt.ts:131-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L131-L157) Unauthorized responses are constructed via `unauthorizedResponse`, which formats a `401` status response carrying a `WWW-Authenticate` header containing the request URL, error type, and error description. Sources: [src/middleware/jwt/jwt.ts:160-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L160-L173) ```typescript function unauthorizedResponse(opts: { ctx: Context error: string errDescription: string statusText?: string }) { return new Response('Unauthorized', { status: 401, statusText: opts.statusText, headers: { 'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`, }, }) } ``` Sources: [src/middleware/jwt/jwt.ts:160-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L160-L173) ## Supported Cryptographic Algorithms and Errors ### Supported JWA Signature Algorithms and Web Crypto Mappings JSON Web Algorithms (JWA) are mapped to underlying Web Crypto API operations via `getKeyAlgorithm` in the JWS utility module. Supported algorithms encompass HMAC-SHA variants (`HS256`, `HS384`, `HS512`), RSA signatures using PKCS#1 v1.5 (`RS256`, `RS384`, `RS512`), RSA Probabilistic Signature Scheme (`PS256`, `PS384`, `PS512`), and Elliptic Curve Digital Signature Algorithm variants (`ES256`, `ES384`, `ES512`) alongside `EdDSA`. | Algorithm | JWA Category | Web Crypto Algorithm Name | Hash Function | Additional Parameters | | :--- | :--- | :--- | :--- | :--- | | `HS256` | Symmetric | `HMAC` | `SHA-256` | — | | `HS384` | Symmetric | `HMAC` | `SHA-384` | — | | `HS512` | Symmetric | `HMAC` | `SHA-512` | — | | `RS256` | Asymmetric | `RSASSA-PKCS1-v1_5` | `SHA-256` | — | | `RS384` | Asymmetric | `RSASSA-PKCS1-v1_5` | `SHA-384` | — | | `RS512` | Asymmetric | `RSASSA-PKCS1-v1_5` | `SHA-512` | — | | `PS256` | Asymmetric | `RSA-PSS` | `SHA-256` | `saltLength: 32` | | `PS384` | Asymmetric | `RSA-PSS` | `SHA-384` | `saltLength: 48` | | `PS512` | Asymmetric | `RSA-PSS` | `SHA-512` | `saltLength: 64` | | `ES256` | Asymmetric | `ECDSA` | `SHA-256` | `namedCurve: 'P-256'` | | `ES384` | Asymmetric | `ECDSA` | `SHA-384` | `namedCurve: 'P-384'` | | `ES512` | Asymmetric | `ECDSA` | `SHA-512` | `namedCurve: 'P-521'` | | `EdDSA` | Asymmetric | `Ed25519` | — | — | Sources: [src/utils/jwt/jwa.ts:7-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwa.ts#L7-L21), [src/utils/jwt/jws.ts:122-211](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L122-L211) ```typescript function getKeyAlgorithm(name: SignatureAlgorithm): KeyAlgorithm { switch (name) { case 'HS256': return { name: 'HMAC', hash: { name: 'SHA-256', }, } satisfies HmacImportParams case 'HS384': return { name: 'HMAC', hash: { name: 'SHA-384', }, } satisfies HmacImportParams case 'HS512': return { name: 'HMAC', hash: { name: 'SHA-512', }, } satisfies HmacImportParams case 'RS256': return { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256', }, } satisfies RsaHashedImportParams case 'RS384': return { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-384', }, } satisfies RsaHashedImportParams case 'RS512': return { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-512', }, } satisfies RsaHashedImportParams case 'PS256': return { name: 'RSA-PSS', hash: { name: 'SHA-256', }, saltLength: 32, // 256 >> 3 } satisfies RsaPssParams & RsaHashedImportParams case 'PS384': return { name: 'RSA-PSS', hash: { name: 'SHA-384', }, saltLength: 48, // 384 >> 3 } satisfies RsaPssParams & RsaHashedImportParams case 'PS512': return { name: 'RSA-PSS', hash: { name: 'SHA-512', }, saltLength: 64, // 512 >> 3, } satisfies RsaPssParams & RsaHashedImportParams case 'ES256': return { name: 'ECDSA', hash: { name: 'SHA-256', }, namedCurve: 'P-256', } satisfies EcdsaParams & EcKeyImportParams case 'ES384': return { name: 'ECDSA', hash: { ``` Sources: [src/utils/jwt/jws.ts:122-211](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L122-L211) > [!CAUTION] > For `PS256`, `PS384`, and `PS512`, the salt length is strictly derived from the hash bit length divided by eight (`256 >> 3` yields `32`, `384 >> 3` yields `48`, and `512 >> 3` yields `64`). Specifying a custom or non-standard salt length outside these Web Crypto mappings will cause signature verification or generation to fail. Sources: [src/utils/jwt/jws.ts:166-194](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts#L166-L194) ### Custom Error Types JWT parsing, validation, and cryptographic routines throw specialized error classes defined in `src/utils/jwt/types.ts`. Each error sets a descriptive message and assigns its `name` property to match the class identifier. | Error Class | Constructor Arguments | Error Message Pattern | | :--- | :--- | :--- | | `JwtAlgorithmNotImplemented` | `alg: string` | `${alg} is not an implemented algorithm` | | `JwtAlgorithmRequired` | none | `JWT verification requires "alg" option to be specified` | | `JwtAlgorithmMismatch` | `expected: string, actual: string` | `JWT algorithm mismatch: expected "${expected}", got "${actual}"` | | `JwtTokenInvalid` | `token: string` | `invalid JWT token: ${token}` | | `JwtTokenNotBefore` | `token: string` | `token (${token}) is being used before it's valid` | | `JwtTokenExpired` | `token: string` | `token (${token}) expired` | | `JwtTokenIssuedAt` | `currentTimestamp: number, iat: number` | `Invalid "iat" claim, must be a valid number lower than "${currentTimestamp}" (iat: "${iat}")` | | `JwtTokenIssuer` | `expected: string \| RegExp, iss: string \| null` | `expected issuer "${expected}", got ${iss ? `"${iss}"` : 'none'} ` | | `JwtHeaderInvalid` | `header: object` | `jwt header is invalid: ${JSON.stringify(header)}` | | `JwtHeaderRequiresKid` | `header: object` | `required "kid" in jwt header: ${JSON.stringify(header)}` | | `JwtSymmetricAlgorithmNotAllowed` | `alg: string` | `symmetric algorithm "${alg}" is not allowed for JWK verification` | | `JwtAlgorithmNotAllowed` | `alg: string, allowedAlgorithms: readonly string[]` | `algorithm "${alg}" is not in the allowed list: [...]` | | `JwtTokenSignatureMismatched` | `token: string` | `token(${token}) signature mismatched` | | `JwtPayloadRequiresAud` | `payload: object` | `required "aud" in jwt payload: ${JSON.stringify(payload)}` | | `JwtTokenAudience` | `expected: string \| string[] \| RegExp, aud: string \| string[]` | `expected audience "${...}", got "${aud}"` | Sources: [src/utils/jwt/types.ts:6-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts#L6-L115) ```typescript export class JwtAlgorithmNotImplemented extends Error { constructor(alg: string) { super(`${alg} is not an implemented algorithm`) this.name = 'JwtAlgorithmNotImplemented' } } export class JwtAlgorithmRequired extends Error { constructor() { super('JWT verification requires "alg" option to be specified') this.name = 'JwtAlgorithmRequired' } } export class JwtAlgorithmMismatch extends Error { constructor(expected: string, actual: string) { super(`JWT algorithm mismatch: expected "${expected}", got "${actual}"`) this.name = 'JwtAlgorithmMismatch' } } export class JwtTokenInvalid extends Error { constructor(token: string) { super(`invalid JWT token: ${token}`) this.name = 'JwtTokenInvalid' } } export class JwtTokenNotBefore extends Error { constructor(token: string) { super(`token (${token}) is being used before it's valid`) this.name = 'JwtTokenNotBefore' } } export class JwtTokenExpired extends Error { constructor(token: string) { super(`token (${token}) expired`) this.name = 'JwtTokenExpired' } } export class JwtTokenIssuedAt extends Error { constructor(currentTimestamp: number, iat: number) { super( `Invalid "iat" claim, must be a valid number lower than "${currentTimestamp}" (iat: "${iat}")` ) this.name = 'JwtTokenIssuedAt' } } export class JwtTokenIssuer extends Error { constructor(expected: string | RegExp, iss: string | null) { super(`expected issuer "${expected}", got ${iss ? `"${iss}"` : 'none'} `) this.name = 'JwtTokenIssuer' } } export class JwtHeaderInvalid extends Error { constructor(header: object) { super(`jwt header is invalid: ${JSON.stringify(header)}`) this.name = 'JwtHeaderInvalid' } } export class JwtHeaderRequiresKid extends Error { constructor(header: object) { super(`required "kid" in jwt header: ${JSON.stringify(header)}`) this.name = 'JwtHeaderRequiresKid' } } export class JwtSymmetricAlgorithmNotAllowed extends Error { constructor(alg: string) { super(`symmetric algorithm "${alg}" is not allowed for JWK verification`) this.name = 'JwtSymmetricAlgorithmNotAllowed' } } export class JwtAlgorithmNotAllowed extends Error { ``` Sources: [src/utils/jwt/types.ts:6-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts#L6-L115) ## Related - [Basic and Bearer Auth](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/basic-and-bearer-auth) - [Secure Headers and CORS](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/secure-headers-and-cors) --- ## Technical docs: Basic and Bearer Auth URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/basic-and-bearer-auth
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/bearer-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts) - [src/utils/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jwt.ts) - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/middleware/basic-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts) - [src/middleware/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts) - [src/middleware/jwk/jwk.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts) - [src/utils/basic-auth.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts) - [src/middleware/jwk/keys.test.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/keys.test.json) - [src/middleware/csrf/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts) - [src/utils/jwt/jws.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/jws.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/utils/headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/headers.ts) - [src/utils/ipaddr.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts) - [src/utils/buffer.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts) - [src/preset/quick.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/preset/quick.ts) - [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/middleware/etag/digest.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts) - [src/utils/jwt/utf8.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/utf8.ts) - [src/utils/encode.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts) - [src/utils/cookie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/cookie.ts) - [src/utils/jwt/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/jwt/types.ts) - [src/utils/accept.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts) - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts)
## Overview Hono provides built-in middleware for HTTP Basic and Bearer Auth to secure API endpoints by validating credentials against static configurations or custom verification handlers. These middlewares inspect incoming request headers, parse authorization schemes, and dispatch standardized HTTP exceptions with `401 Unauthorized` status codes and `WWW-Authenticate` challenge headers when verification fails. Sources: [src/middleware/basic-auth/index.ts:31-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L31-L46), [src/middleware/bearer-auth/index.ts:88-89](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L88-L89) To prevent timing side-channel attacks during credential comparison, the system utilizes constant-time string and buffer comparison algorithms implemented within utility modules. Sources: [src/utils/buffer.ts:29-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L63) ## Basic Authentication Flow ### Credential Matching Execution Walkthrough The `basicAuth` middleware accepts an options object supporting either static username/password pairs or a custom `verifyUser` asynchronous callback function. The public configuration options also accept an optional `realm`, a `hashFunction` for credential normalization, an `invalidUserMessage` string, object, or message function, and an `onAuthSuccess` callback hook. If neither static credentials nor a `verifyUser` function are supplied, initialization throws an error. Sources: [src/middleware/basic-auth/index.ts:14-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L14-L30), [src/middleware/basic-auth/index.ts:80-91](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L80-L91) | Option Key | Type | Default Value | Description | | :--- | :--- | :--- | :--- | | `username` | `string` | — | Static username for authentication matching | | `password` | `string` | — | Static password for authentication matching | | `verifyUser` | `Function` | — | Custom verification handler taking `(username, password, c)` | | `realm` | `string` | `"Secure Area"` | Realm attribute populated in the `WWW-Authenticate` header | | `hashFunction` | `Function` | `sha256` | Hash function utilized during secure credential comparison | | `invalidUserMessage` | `string \| object \| Function` | `"Unauthorized"` | Response body content returned on validation failure | | `onAuthSuccess` | `Function` | — | Callback function invoked upon successful authentication | Sources: [src/middleware/basic-auth/index.ts:36-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L36-L43), [src/middleware/basic-auth/index.ts:93-99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L93-L99) > [!NOTE] > When static `username` and `password` properties are specified in the configuration object alongside rest parameters (`...users`), they are prepended to the internal user verification array via `users.unshift()`. Sources: [src/middleware/basic-auth/index.ts:81-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L81-L83), [src/middleware/basic-auth/index.ts:101-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L101-L103) When an incoming request is intercepted, the handler extracts and parses authorization credentials from the request headers using the basic auth utility function, checking the provided username and password against configured accounts or the custom verification handler via the execution chain: `basicAuth` → `timingSafeEqual` → `timingSafeEqualString` → `constantTimeEqualString`. Sources: [src/middleware/basic-auth/index.ts:105-131](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L105-L131), [src/utils/buffer.ts:29-96](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L96) 1. `basicAuth` invokes `auth(ctx.req.raw)` to extract the decoded request username and password, then iterates through configured users to invoke `timingSafeEqual(user.username, requestUser.username, options.hashFunction)` and `timingSafeEqual(user.password, requestUser.password, options.hashFunction)` via `Promise.all`. Sources: [src/middleware/basic-auth/index.ts:106-121](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L106-L121) 2. `timingSafeEqual` checks argument types and routes string inputs to `timingSafeEqualString`. Sources: [src/utils/buffer.ts:76-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L83) 3. `timingSafeEqualString` resolves the active hash function (defaulting to `sha256`), computes hashed byte representations of both strings in parallel via `Promise.all`, and passes the resulting digests to `constantTimeEqualString`. Sources: [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63) 4. `constantTimeEqualString` evaluates character codes across the maximum length utilizing bitwise operations to accumulate differences without early exits. Sources: [src/utils/buffer.ts:29-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L40) ```mermaid sequenceDiagram participant Index as src/middleware/basic-auth/index.ts participant Buffer as src/utils/buffer.ts Index->>Buffer: basicAuth() calls timingSafeEqual() Buffer->>Buffer: timingSafeEqual() calls timingSafeEqualString() Buffer->>Buffer: timingSafeEqualString() calls constantTimeEqualString() ``` Sources: [src/middleware/basic-auth/index.ts:118-121](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L118-L121), [src/utils/buffer.ts:76-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L83), [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63), [src/utils/buffer.ts:29-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L40) ## Parsing Authorization Credentials ### Credential Extraction and Decoding The [Utilities and Encoding](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/utilities-and-encoding) page documents how low-level helpers manage character encoding [src/utils/encode.ts:1-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L1-L4). Incoming HTTP requests are processed by the `auth` helper, which reads the `Authorization` header and matches it against `CREDENTIALS_REGEXP` to isolate the Base64-encoded payload portion [src/utils/basic-auth.ts:3-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L3-L10). If the header is missing or fails the regular expression pattern, the function immediately returns `undefined` [src/utils/basic-auth.ts:10-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L10-L13). Sources: [src/utils/basic-auth.ts:3-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L3-L13), [src/utils/encode.ts:1-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L1-L4) ### Execution Walkthrough and Sequence 1. `basicAuth` invokes `auth(ctx.req.raw)` to retrieve credentials from the raw request object [src/middleware/basic-auth/index.ts:106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L106). Sources: [src/middleware/basic-auth/index.ts:106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L106) 2. `auth` executes `CREDENTIALS_REGEXP.exec` on the header string, captures group `1`, and passes it to `decodeBase64` [[src/utils/basic-auth.ts:10], [src/utils/basic-auth.ts:18]]. Sources: [src/utils/basic-auth.ts:10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L10], [src/utils/basic-auth.ts:18) 3. `decodeBase64` invokes `atob(str)` and constructs a `Uint8Array` using byte character codes [src/utils/encode.ts:25-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L25-L33). Sources: [src/utils/encode.ts:25-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L25-L33) ```mermaid sequenceDiagram participant BasicAuth as src/middleware/basic-auth/index.ts participant BasicAuthUtil as src/utils/basic-auth.ts participant EncodeUtil as src/utils/encode.ts BasicAuth->>BasicAuthUtil: auth(ctx.req.raw) BasicAuthUtil->>EncodeUtil: decodeBase64(match[1]) EncodeUtil-->>BasicAuthUtil: Returns Uint8Array bytes ``` Sources: [src/middleware/basic-auth/index.ts:106](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L106), [src/utils/basic-auth.ts:10-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L10-L18), [src/utils/encode.ts:25-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/encode.ts#L25-L33) ### Regular Expressions and Sanitization | Constant Name | Regular Expression Pattern | Purpose | | :--- | :--- | :--- | | `CREDENTIALS_REGEXP` | `/^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/` | Matches and extracts the Base64 token following the Basic scheme prefix. | | `USER_PASS_REGEXP` | `/^([^:]*):(.*)$/` | Splits the decoded string into username and password components across the first colon. | Sources: [src/utils/basic-auth.ts:3-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L3-L4) > [!WARNING] > If an invalid string is passed to `atob()`, a `DOMException` is thrown; the `auth` function catches this exception inside a `try...catch` block and safely returns `undefined` rather than crashing the [request lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle). Sources: [src/utils/basic-auth.ts:15-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/basic-auth.ts#L15-L20) ## Bearer Authentication Enforcement ### Bearer Options and Header Processing The `bearerAuth` middleware requires options containing either a `token` (string or array of strings) or a `verifyToken` function. Optional configurations include `realm`, `prefix`, `headerName`, `hashFunction`, and customized error responses via `noAuthenticationHeader`, `invalidAuthenticationHeader`, and `invalidToken`. If neither `token` nor `verifyToken` is provided, the middleware throws an initialization error. Sources: [src/middleware/bearer-auth/index.ts:22-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L22-L50), [src/middleware/bearer-auth/index.ts:107-109](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L107-L109) | Option Name | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `token` | `string \| string[]` | `undefined` | The static token string or array of acceptable tokens. | | `verifyToken` | `(token: string, c: Context) => boolean \| Promise` | `undefined` | Custom token verification callback function. | | `realm` | `string` | `''` | Authentication realm string included in challenge headers. | | `prefix` | `string` | `'Bearer'` | Expected scheme prefix preceding the token. | | `headerName` | `string` | `'Authorization'` | Custom header name to inspect instead of `Authorization`. | | `hashFunction` | `Function` | `sha256` | Custom hashing function used during token comparison. | Sources: [src/middleware/bearer-auth/index.ts:22-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L22-L50), [src/middleware/bearer-auth/index.ts:110-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L110-L115), [src/utils/buffer.ts:50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L50) > [!NOTE] > When `prefix` is set to an empty string `''`, scheme prefix validation is bypassed entirely, and the entire header value is treated directly as the token string. Sources: [src/middleware/bearer-auth/index.ts:172-174](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L172-L174) ### Execution Walkthrough and Sequence 1. `bearerAuth` receives the request and inspects the specified HTTP header using `c.req.header(options.headerName || HEADER)`. Sources: [src/middleware/bearer-auth/index.ts:156-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L156-L157) 2. If the header is missing, it dispatches an unauthorized exception via `throwHTTPException` with a 401 status. Sources: [src/middleware/bearer-auth/index.ts:158-168](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L158-L168) 3. If present, it validates the scheme prefix case-insensitively, trims leading whitespace, and tests the extracted token against `tokenRegexp` (`^[A-Za-z0-9._~+/-]+=*$`). Sources: [src/middleware/bearer-auth/index.ts:12-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L12-L19), [src/middleware/bearer-auth/index.ts:175-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L175-L182) 4. If token validation fails, a 400 Bad Request exception is thrown. Sources: [src/middleware/bearer-auth/index.ts:182-192](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L182-L192) 5. Otherwise, credential matching delegates to `verifyToken` or calls `timingSafeEqual`. Sources: [src/middleware/bearer-auth/index.ts:195-206](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L195-L206) 6. `timingSafeEqual` invokes `timingSafeEqualString`. Sources: [src/utils/buffer.ts:76-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L83) 7. `timingSafeEqualString` invokes `constantTimeEqualString` for byte and hash verification. Sources: [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63) ```mermaid sequenceDiagram participant BearerAuth as src/middleware/bearer-auth/index.ts participant BufferUtil as src/utils/buffer.ts BearerAuth->>BufferUtil: timingSafeEqual(options.token, tokenValue, options.hashFunction) BufferUtil->>BufferUtil: timingSafeEqualString(a, b, hashFunction) BufferUtil->>BufferUtil: constantTimeEqualString(sa, sb) ``` Sources: [src/middleware/bearer-auth/index.ts:198](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L198), [src/utils/buffer.ts:76-83](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L83), [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63), [src/utils/buffer.ts:29-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L40) ## Timing-Attack Mitigation ### Constant-Time Comparison Operations Hono implements timing-attack mitigation utilities in `src/utils/buffer.ts` to prevent attackers from inferring secret tokens or passwords via response latency side channels. The lowest-level primitive, `constantTimeEqualString`, processes two strings character by character without short-circuiting on mismatch: ```typescript const constantTimeEqualString = (a: string, b: string): boolean => { const aLen = a.length const bLen = b.length const maxLen = Math.max(aLen, bLen) let out = aLen ^ bLen for (let i = 0; i < maxLen; i++) { const aChar = i < aLen ? a.charCodeAt(i) : 0 const bChar = i < bLen ? b.charCodeAt(i) : 0 out |= aChar ^ bChar } return out === 0 } ``` Sources: [src/utils/buffer.ts:29-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L29-L40) > [!CAUTION] > Length differences between strings are accumulated into the XOR accumulator via `aLen ^ bLen`, preventing length-extension leaks from exiting early when string lengths diverge. Sources: [src/utils/buffer.ts:33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L33) ### ArrayBuffer and String Equivalence Higher-level comparison functions handle binary `ArrayBuffer` instances as well as hashed and unhashed strings. The `equal` function compares two `ArrayBuffer` instances using a DataView iteration loop: ```typescript export const equal = (a: ArrayBuffer, b: ArrayBuffer): boolean => { if (a === b) { return true } if (a.byteLength !== b.byteLength) { return false } const va = new DataView(a) const vb = new DataView(b) let i = va.byteLength while (i--) { if (va.getUint8(i) !== vb.getUint8(i)) { return false } } return true } ``` Sources: [src/utils/buffer.ts:8-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L8-L27) The `timingSafeEqualString` function wraps string hashing and comparison. By default, if no custom `hashFunction` is provided, it falls back to `sha256`: ```typescript const timingSafeEqualString = async ( a: string, b: string, hashFunction?: StringHashFunction ): Promise => { if (!hashFunction) { hashFunction = sha256 } const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]) if (sa == null || sb == null || typeof sa !== 'string' || typeof sb !== 'string') { return false } const hashEqual = constantTimeEqualString(sa, sb) const originalEqual = constantTimeEqualString(a, b) return hashEqual && originalEqual } ``` Sources: [src/utils/buffer.ts:44-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L44-L63) > [!NOTE] > `timingSafeEqualString` evaluates both `constantTimeEqualString(sa, sb)` on the hashed outputs and `constantTimeEqualString(a, b)` on the raw inputs concurrently, returning true only if both comparisons succeed. Sources: [src/utils/buffer.ts:53-62](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L53-L62) The exported `timingSafeEqual` entry point normalizes inputs and routes execution depending on whether parameters are strings or generic objects/booleans: ```typescript export const timingSafeEqual: TimingSafeEqual = async ( a, b, hashFunction?: Function ): Promise => { if (typeof a === 'string' && typeof b === 'string') { return timingSafeEqualString(a, b, hashFunction as StringHashFunction) } if (!hashFunction) { hashFunction = sha256 } const [sa, sb] = await Promise.all([hashFunction(a), hashFunction(b)]) if (!sa || !sb || typeof sa !== 'string' || typeof sb !== 'string') { return false } return timingSafeEqualString(sa, sb) } ``` Sources: [src/utils/buffer.ts:76-96](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts#L76-L96) ## Authentication Challenges and Error Dispatch ### HTTPException Instantiation and Response Generation When authentication fails across Hono's authentication middlewares, error handling is dispatched via `HTTPException` combined with custom `Response` instances. The `basicAuth` middleware evaluates the parsed user credentials against configured options or user lists. Upon failure, it constructs a 401 Unauthorized status response containing the `WWW-Authenticate` header populated with the escaped realm name. If `invalidUserMessage` is configured as a function or an object, it is dynamically serialized into a text or JSON payload before throwing the `HTTPException`: ```typescript // Invalid user. const status = 401 const headers = { 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"', } const responseMessage = typeof options.invalidUserMessage === 'function' ? await options.invalidUserMessage(ctx) : options.invalidUserMessage const res = typeof responseMessage === 'string' ? new Response(responseMessage, { status, headers }) : new Response(JSON.stringify(responseMessage), { status, headers: { ...headers, 'content-type': 'application/json', }, }) throw new HTTPException(status, { res }) } ``` Sources: [src/middleware/basic-auth/index.ts:132-152](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L132-L152) Similarly, the `bearerAuth` middleware defines a private `throwHTTPException` helper function to encapsulate status codes, challenge headers, and message body construction. Depending on the specific failure branch—such as missing headers, malformed requests, or invalid tokens—it issues status codes 401, 400, or 401 respectively. Sources: [src/middleware/bearer-auth/index.ts:122-154](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L122-L154) > [!WARNING] > Realms containing double quotes are automatically escaped via `options.realm?.replace(/"/g, '\\"')` prior to header injection to prevent header injection vulnerabilities. Sources: [src/middleware/basic-auth/index.ts:135](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L135), [src/middleware/bearer-auth/index.ts:117](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L117) ### WWW-Authenticate Challenge Construction The construction of challenge headers differs between schemes based on whether options specify plain strings, objects, or callback functions. The `bearerAuth` middleware processes `wwwAuthenticateHeader` parameters by checking their type. If an object is supplied, its entries are mapped into comma-separated key-value pairs appended to the challenge prefix: ```typescript const wwwAuthenticateHeaderValue: string | object = typeof wwwAuthenticateHeader === 'function' ? await wwwAuthenticateHeader(c) : wwwAuthenticateHeader const headers = { 'WWW-Authenticate': typeof wwwAuthenticateHeaderValue === 'string' ? wwwAuthenticateHeaderValue : `${wwwAuthenticatePrefix}${Object.entries(wwwAuthenticateHeaderValue) .map(([key, value]) => `${key}="${value}"`) .join(',')}`, } ``` Sources: [src/middleware/bearer-auth/index.ts:128-140](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L128-L140) For JSON Web Token workflows in `jwt` and `jwk` middlewares, failed verifications or missing tokens trigger `unauthorizedResponse`, which formats challenge headers including the current request URL, error codes, and detailed descriptions: ```typescript function unauthorizedResponse(opts: { ctx: Context error: string errDescription: string statusText?: string }) { return new Response('Unauthorized', { status: 401, statusText: opts.statusText, headers: { 'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`, }, }) } ``` Sources: [src/middleware/jwt/jwt.ts:160-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L160-L173), [src/middleware/jwk/jwk.ts:170-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts#L170-L182) | Middleware | Default Status Code | Default WWW-Authenticate Challenge | Message Payload Handling | | :--- | :--- | :--- | :--- | | `basicAuth` | `401` | `Basic realm="..."` | Text or JSON via `invalidUserMessage` | | `bearerAuth` (Missing) | `401` | `Bearer realm="..."` | Text or JSON via `noAuthenticationHeader.message` | | `bearerAuth` (Invalid Request) | `400` | `Bearer error="invalid_request"` | Text or JSON via `invalidAuthenticationHeader.message` | | `bearerAuth` (Invalid Token) | `401` | `Bearer error="invalid_token"` | Text or JSON via `invalidToken.message` | | `jwt` / `jwk` | `401` | `Bearer realm="...",error="...",error_description="..."` | Static string `'Unauthorized'` | Sources: [src/middleware/basic-auth/index.ts:133-151](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts#L133-L151), [src/middleware/bearer-auth/index.ts:160-215](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts#L160-L215), [src/middleware/jwt/jwt.ts:160-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts#L160-L173), [src/middleware/jwk/jwk.ts:170-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts#L170-L182) ## Related - [JWT and JWK](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/jwt-and-jwk) --- ## Technical docs: Secure Headers and CORS URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/secure-headers-and-cors
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/middleware/secure-headers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/index.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/middleware/csrf/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/middleware/jwk/jwk.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts) - [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/middleware/etag/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts) - [src/middleware/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts) - [src/middleware/cors/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts) - [src/middleware/bearer-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/middleware/secure-headers/permissions-policy.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/permissions-policy.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/utils/headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/headers.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/helper/cookie/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/cookie/index.ts) - [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts) - [src/middleware/timing/timing.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts) - [src/middleware/method-override/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts) - [src/utils/cookie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/cookie.ts) - [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/helper/ssg/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/index.ts) - [src/helper/ssg/middleware.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/middleware.ts) - [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts) - [src/middleware/jwk/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/index.ts) - [src/middleware/powered-by/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/powered-by/index.ts)
## Overview Hono provides robust middleware components for enforcing web security policies and managing cross-origin resource sharing. The `secureHeaders` middleware injects foundational defense headers such as `X-Content-Type-Options`, `X-Frame-Options`, `Strict-Transport-Security`, and dynamic Content Security Policy rules complete with cryptographic nonce generation. Complementing this, the `cors` middleware handles complex browser preflight requests, origin validation, and credentials configuration to safely permit cross-origin access. Sources: [src/middleware/secure-headers/secure-headers.ts:69-145](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L69-L145), [src/middleware/cors/index.ts:9-148](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts#L9-L148) ## Secure Headers Middleware Architecture ### Public Entry Points and Types The secure headers middleware exports public entry points and type definitions via `src/middleware/secure-headers/index.ts` and `src/middleware/secure-headers/secure-headers.ts`. It exposes the `secureHeaders` middleware handler function, the `NONCE` content security policy handler constant, `ContentSecurityPolicyOptionHandler`, and `SecureHeadersVariables` which augment Hono's `ContextVariableMap` with `secureHeadersNonce`. Sources: [src/middleware/secure-headers/index.ts:1-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/index.ts#L1-L8), [src/middleware/secure-headers/secure-headers.ts:6-145](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L6-L145) ### Default Header Mappings and Configuration Lifecycle The middleware maintains a static mapping of header identifiers to default header names and fallback directive values through `HEADERS_MAP` and establishes baseline options via `DEFAULT_OPTIONS`. Each policy header can be toggled via boolean configuration or overridden with custom string values. | Option Key | HTTP Header Name | Default Value / State | | :--- | :--- | :--- | | `crossOriginEmbedderPolicy` | `Cross-Origin-Embedder-Policy` | `require-corp` (Disabled by default: `false`) | | `crossOriginResourcePolicy` | `Cross-Origin-Resource-Policy` | `same-origin` (Enabled: `true`) | | `crossOriginOpenerPolicy` | `Cross-Origin-Opener-Policy` | `same-origin` (Enabled: `true`) | | `originAgentCluster` | `Origin-Agent-Cluster` | `?1` (Enabled: `true`) | | `referrerPolicy` | `Referrer-Policy` | `no-referrer` (Enabled: `true`) | | `strictTransportSecurity` | `Strict-Transport-Security` | `max-age=15552000; includeSubDomains` (Enabled: `true`) | | `xContentTypeOptions` | `X-Content-Type-Options` | `nosniff` (Enabled: `true`) | | `xDnsPrefetchControl` | `X-DNS-Prefetch-Control` | `off` (Enabled: `true`) | | `xDownloadOptions` | `X-Download-Options` | `noopen` (Enabled: `true`) | | `xFrameOptions` | `X-Frame-Options` | `SAMEORIGIN` (Enabled: `true`) | | `xPermittedCrossDomainPolicies` | `X-Permitted-Cross-Domain-Policies` | `none` (Enabled: `true`) | | `xXssProtection` | `X-XSS-Protection` | `0` (Enabled: `true`) | Sources: [src/middleware/secure-headers/secure-headers.ts:94-124](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L94-L124) > [!NOTE] > The `secureHeadersNonce` variable checks the current context state for an existing cryptographic nonce before executing `generateNonce()`, utilizing `crypto.getRandomValues()` on a 16-byte `Uint8Array` combined with `encodeBase64()`. Sources: [src/middleware/secure-headers/secure-headers.ts:131-145](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L131-L145) ## Content Security Policy Configuration ### CSP Options and Dynamic Nonce Generation The `secureHeaders` middleware supports configuring `contentSecurityPolicy` and `contentSecurityPolicyReportOnly` options via `ContentSecurityPolicyOptions`. Each directive accepts an array of string values or `ContentSecurityPolicyOptionHandler` callbacks. The built-in `NONCE` handler checks [context storage](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/context-storage) for an existing `secureHeadersNonce` variable; if absent, it allocates a 16-byte `Uint8Array`, populates it using `crypto.getRandomValues()`, encodes the buffer into base64 via `encodeBase64()`, stores it in the context, and returns the formatted `'nonce-'` string. ```typescript export const NONCE: ContentSecurityPolicyOptionHandler = (ctx) => { const key = 'secureHeadersNonce' const init = ctx.get(key) const nonce = init || generateNonce() if (init == null) { ctx.set(key, nonce) } return `'nonce-${nonce}'` } ``` Sources: [src/middleware/secure-headers/secure-headers.ts:15-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L15-L44), [src/middleware/secure-headers/secure-headers.ts:131-145](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L131-L145) > [!NOTE] > Reusing the `NONCE` handler across multiple directives within the same [request lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle) retrieves the cached nonce from the context rather than generating a new random buffer for each directive. Sources: [src/middleware/secure-headers/secure-headers.ts:137-143](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L137-L143) ### Supported Content Security Policy Directives | Option Property | Directive Name / Purpose | Value Type | | :--- | :--- | :--- | | `defaultSrc` | `default-src` fallback fetch directive | `ContentSecurityPolicyOptionValue` | | `baseUri` | `base-uri` restriction for `` elements | `ContentSecurityPolicyOptionValue` | | `childSrc` | `child-src` for web workers and nested browsing contexts | `ContentSecurityPolicyOptionValue` | | `connectSrc` | `connect-src` targets for fetch, XHR, and WebSockets | `ContentSecurityPolicyOptionValue` | | `fontSrc` | `font-src` valid sources for loading fonts | `ContentSecurityPolicyOptionValue` | | `formAction` | `form-action` valid endpoints for form submissions | `ContentSecurityPolicyOptionValue` | | `frameAncestors` | `frame-ancestors` embedding restriction for frames | `ContentSecurityPolicyOptionValue` | | `frameSrc` | `frame-src` sources for nested browsing contexts | `ContentSecurityPolicyOptionValue` | | `imgSrc` | `img-src` valid sources for images | `ContentSecurityPolicyOptionValue` | | `manifestSrc` | `manifest-src` sources for application manifests | `ContentSecurityPolicyOptionValue` | | `mediaSrc` | `media-src` sources for audio and video elements | `ContentSecurityPolicyOptionValue` | | `objectSrc` | `object-src` sources for ``, ``, and `` | `ContentSecurityPolicyOptionValue` | | `reportTo` | `report-to` group destination identifier | `string` | | `reportUri` | `report-uri` endpoint URL or array of URLs | `string | string[]` | | `sandbox` | `sandbox` applied sandbox restrictions | `ContentSecurityPolicyOptionValue` | | `scriptSrc` | `script-src` valid sources for JavaScript | `ContentSecurityPolicyOptionValue` | | `scriptSrcAttr` | `script-src-attr` valid sources for inline script event handlers | `ContentSecurityPolicyOptionValue` | | `scriptSrcElem` | `script-src-elem` valid sources for script elements | `ContentSecurityPolicyOptionValue` | | `styleSrc` | `style-src` valid sources for stylesheets | `ContentSecurityPolicyOptionValue` | | `styleSrcAttr` | `style-src-attr` valid sources for inline style attributes | `ContentSecurityPolicyOptionValue` | | `styleSrcElem` | `style-src-elem` valid sources for style elements | `ContentSecurityPolicyOptionValue` | | `upgradeInsecureRequests` | `upgrade-insecure-requests` flag directive | `ContentSecurityPolicyOptionValue` | | `workerSrc` | `worker-src` valid sources for worker scripts | `ContentSecurityPolicyOptionValue` | | `requireTrustedTypesFor` | `require-trusted-types-for` policy enforcement | `ContentSecurityPolicyOptionValue` | | `trustedTypes` | `trusted-types` policy names | `ContentSecurityPolicyOptionValue` | Sources: [src/middleware/secure-headers/secure-headers.ts:18-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L18-L44) ## Permissions Policy Directives ### Directive Mappings and Allowlist Formatting The permissions-policy configuration handles W3C feature controls through `PermissionsPolicyOptions`, mapping directive keys to either an array of allowed origin strings or a boolean flag. The allowlist accepts standard keyword identifiers including `'*'`, `'self'`, `'src'`, and `'none'`, or custom origin strings. ```typescript type PermissionsPolicyValue = '*' | 'self' | 'src' | 'none' | string type PermissionsPolicyOptions = Partial< Record > ``` Sources: [src/middleware/secure-headers/secure-headers.ts:61-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L61-L65) > [!NOTE] > Setting a permissions policy directive to `true` compiles to the allowlist keyword `'self'`, while `false` restricts the feature completely via `'none'`. Sources: [src/middleware/secure-headers/secure-headers.ts:63-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L63-L65) ### Standardized, Proposed, and Experimental Features The `PermissionsPolicyDirective` union type incorporates standardized specifications, proposed features still undergoing standardization, and experimental features available for developer testing. ```typescript export type PermissionsPolicyDirective = | StandardizedFeatures | ProposedFeatures | ExperimentalFeatures ``` Sources: [src/middleware/secure-headers/permissions-policy.ts:3-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/permissions-policy.ts#L3-L7) | Feature Category | Directive Identifiers | | :--- | :--- | | Standardized Features | `accelerometer`, `ambientLightSensor`, `attributionReporting`, `autoplay`, `battery`, `bluetooth`, `camera`, `chUa`, `chUaArch`, `chUaBitness`, `chUaFullVersion`, `chUaFullVersionList`, `chUaMobile`, `chUaModel`, `chUaPlatform`, `chUaPlatformVersion`, `chUaWow64`, `computePressure`, `crossOriginIsolated`, `directSockets`, `displayCapture`, `encryptedMedia`, `executionWhileNotRendered`, `executionWhileOutOfViewport`, `fullscreen`, `geolocation`, `gyroscope`, `hid`, `identityCredentialsGet`, `idleDetection`, `keyboardMap`, `magnetometer`, `microphone`, `midi`, `navigationOverride`, `payment`, `pictureInPicture`, `publickeyCredentialsGet`, `screenWakeLock`, `serial`, `storageAccess`, `syncXhr`, `usb`, `webShare`, `windowManagement`, `xrSpatialTracking` | | Proposed Features | `clipboardRead`, `clipboardWrite`, `gamepad`, `sharedAutofill`, `speakerSelection` | | Experimental Features | `allScreensCapture`, `browsingTopics`, `capturedSurfaceControl`, `conversionMeasurement`, `digitalCredentialsGet`, `focusWithoutUserActivation`, `joinAdInterestGroup`, `localFonts`, `runAdAuction`, `smartCard`, `syncScript`, `trustTokenRedemption`, `unload`, `verticalScroll` | Sources: [src/middleware/secure-headers/permissions-policy.ts:11-86](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/permissions-policy.ts#L11-L86) ## Reporting Endpoints and Transport Security ### Transport Security and Referrer Protection The secure headers middleware manages transport encryption enforcement and information leakage prevention through dedicated configuration options. Strict-Transport-Security (HSTS) and Referrer-Policy headers leverage overridable header definitions that accept either boolean flags or explicit custom strings. When enabled via default options, HSTS defaults to a max-age of 15,552,000 seconds with subdomain inclusion, while referrer policy restricts leakage via `no-referrer`. | Option Name | Default Header Value | Type | Purpose | | :--- | :--- | :--- | :--- | | `strictTransportSecurity` | `Strict-Transport-Security: max-age=15552000; includeSubDomains` | `overridableHeader` | Enforces secure HTTPS connections and subdomain protection | | `referrerPolicy` | `Referrer-Policy: no-referrer` | `overridableHeader` | Controls how referrer information is included with requests | Sources: [src/middleware/secure-headers/secure-headers.ts:67-79](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L67-L79), [src/middleware/secure-headers/secure-headers.ts:99-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L99-L100), [src/middleware/secure-headers/secure-headers.ts:114-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L114-L115) > [!NOTE] > An `overridableHeader` type resolves as either a boolean toggle controlling default behavior or an explicit string value overriding the header completely. Sources: [src/middleware/secure-headers/secure-headers.ts:67-67](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L67-L67) ### Report-To and Reporting-Endpoints Configuration The middleware supports modern browser error reporting and diagnostic infrastructure through `ReportToOptions` and `ReportingEndpointOptions` interfaces. These options configure destination groups and endpoint URLs for reporting API violations, CSP breaches, and deprecation warnings. ```typescript interface ReportToOptions { group: string max_age: number endpoints: ReportToEndpoint[] } interface ReportToEndpoint { url: string } interface ReportingEndpointOptions { name: string url: string } ``` Sources: [src/middleware/secure-headers/secure-headers.ts:46-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L46-L59) ## Cross Origin Resource Sharing Architecture ### CORS Options and Initialization The CORS middleware entry point `cors()` accepts a configuration object defining `origin`, `allowMethods`, `allowHeaders`, `maxAge`, `credentials`, and `exposeHeaders`. When omitted, default options initialize `origin` to `*`, `allowMethods` to `['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']`, while `allowHeaders` and `exposeHeaders` default to empty arrays. | Option Name | Default Value | Type | Purpose | | :--- | :--- | :--- | :--- | | `origin` | `*` | `string \| string[] \| ((origin: string, c: Context) => Promise \| string \| undefined \| null)` | Sets `Access-Control-Allow-Origin` | | `allowMethods` | `['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']` | `string[] \| ((origin: string, c: Context) => Promise \| string[])` | Sets `Access-Control-Allow-Methods` | | `allowHeaders` | `[]` | `string[]` | Sets `Access-Control-Allow-Headers` | | `maxAge` | `undefined` | `number` | Sets `Access-Control-Max-Age` | | `credentials` | `undefined` | `boolean` | Sets `Access-Control-Allow-Credentials` | | `exposeHeaders` | `[]` | `string[]` | Sets `Access-Control-Expose-Headers` | Sources: [src/middleware/cors/index.ts:9-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts#L9-L35), [src/middleware/cors/index.ts:63-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts#L63-L70) > [!NOTE] > The origin resolver handles three input types: wildcard strings (`*`), literal matching strings, arrays of allowed origins, and custom async or sync callback functions. Sources: [src/middleware/cors/index.ts:72-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts#L72-L84) ### Preflight and Response Header Execution During a request execution lifecycle, the middleware extracts the incoming `Origin` header and queries `findAllowOrigin`. If an allowed origin is returned, it sets `Access-Control-Allow-Origin`. When `credentials` is enabled, `Access-Control-Allow-Credentials` is set to `true`. If `exposeHeaders` contains items, they are joined by commas and assigned to `Access-Control-Expose-Headers`. ```typescript if (c.req.method === 'OPTIONS') { if (opts.origin !== '*') { set('Vary', 'Origin') } if (opts.maxAge != null) { set('Access-Control-Max-Age', opts.maxAge.toString()) } const allowMethods = await findAllowMethods(c.req.header('origin') || '', c) if (allowMethods.length) { set('Access-Control-Allow-Methods', allowMethods.join(',')) } let headers = opts.allowHeaders if (!headers?.length) { const requestHeaders = c.req.header('Access-Control-Request-Headers') if (requestHeaders) { headers = requestHeaders.split(/\s*,\s*/) } } if (headers?.length) { set('Access-Control-Allow-Headers', headers.join(',')) c.res.headers.append('Vary', 'Access-Control-Request-Headers') } c.res.headers.delete('Content-Length') c.res.headers.delete('Content-Type') return new Response(null, { headers: c.res.headers, status: 204, statusText: 'No Content', }) } ``` Sources: [src/middleware/cors/index.ts:114-148](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts#L114-L148) For `OPTIONS` preflight requests, the middleware appends `Vary: Origin` if `origin` is not `*`, populates `Access-Control-Max-Age` if `maxAge` is defined, and resolves allowed methods via `findAllowMethods`. If `allowHeaders` is empty, it falls back to parsing the `Access-Control-Request-Headers` request header. Finally, it deletes `Content-Length` and `Content-Type` headers and returns an HTTP 204 `No Content` response with the assembled headers. For standard requests, it invokes `next()` and appends `Vary: Origin` post-invocation if the origin option is restrictive. Sources: [src/middleware/cors/index.ts:114-156](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts#L114-L156) ## Related - [CSRF and Body Limit](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/csrf-and-body-limit) - [IP Restriction](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/ip-restriction) --- ## Technical docs: CSRF and Body Limit URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/csrf-and-body-limit
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/body-limit/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts) - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/middleware/csrf/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/middleware/method-override/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/utils/body.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts) - [src/middleware/jwk/jwk.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/jwk.ts) - [src/middleware/jwt/jwt.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/jwt.ts) - [src/validator/validator.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/validator/validator.ts) - [src/middleware/cors/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts) - [src/middleware/etag/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts) - [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts) - [src/middleware/bearer-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/middleware/compress/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/utils/buffer.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts) - [src/middleware/etag/digest.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts) - [src/client/fetch-result-please.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/client/fetch-result-please.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/adapter/vercel/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/conninfo.ts) - [src/adapter/lambda-edge/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts) - [src/helper/streaming/utils.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/utils.ts) - [src/middleware/secure-headers/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/index.ts) - [src/utils/compress.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/compress.ts) - [src/middleware/request-id/request-id.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts) - [src/middleware/secure-headers/permissions-policy.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/permissions-policy.ts) - [src/middleware/jwk/keys.test.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/keys.test.json)
## Overview Hono provides built-in middleware to protect web applications against Cross-Site Request Forgery (CSRF) and control inbound request payload sizes[CSRF Protection Middleware for Hono](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L1-L3), [Body Limit Middleware for Hono](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts#L1-L4). The CSRF middleware evaluates request security by validating `Origin` headers and `Sec-Fetch-Site` values against safe and mutating HTTP method checks[CSRF Protection Middleware for Hono](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L32-L36). Concurrently, the body limit middleware safeguards server resources by inspecting `Content-Length` headers or incrementally tracking streaming request bodies against configured maximum size limits[Body Limit Middleware for Hono](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts#L18-L25), [src/middleware/body-limit/index.ts:61-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts#L61-L94). Together, these components enforce robust request boundaries across diverse edge and serverless environments. Sources: [CSRF Protection Middleware for Hono](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L1-L3), [Body Limit Middleware for Hono](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts#L1-L4), [src/middleware/csrf/index.ts:32-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L32-L36), [src/middleware/body-limit/index.ts:18-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts#L18-L25), [src/middleware/body-limit/index.ts:61-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts#L61-L94) ## Cross-Site Request Forgery Protection Architecture ### Public API Surface and Method Checks Hono exports the `csrf()` factory function which returns a standard `MiddlewareHandler`[src/middleware/csrf/index.ts:94-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L94-L150). The middleware evaluates incoming requests against safe and mutating HTTP method classifications[src/middleware/csrf/index.ts:139-144](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L139-L144). Safe methods are matched using the regular expression `/^(GET|HEAD)$/`, exempting read-only requests from validation[src/middleware/csrf/index.ts:28|28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L28-L28), [src/middleware/csrf/index.ts:139-140](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L139-L140). Mutating requests undergo inspection only if their `content-type` header matches form element submission patterns defined by `/^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i`[src/middleware/csrf/index.ts:29-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L29-L30), [src/middleware/csrf/index.ts:140-141](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L140-L141). If both `sec-fetch-site` and `origin` validations fail on a matching mutating request, the middleware instantiates a `Response` with body `'Forbidden'` and status `403`, throwing an `HTTPException(403)`[src/middleware/csrf/index.ts:142-147](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L142-L147). Otherwise, control advances via `await next()`[src/middleware/csrf/index.ts:149-149](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L149-L149). ```typescript const isSafeMethodRe = /^(GET|HEAD)$/ const isRequestedByFormElementRe = /^\b(application\/x-www-form-urlencoded|multipart\/form-data|text\/plain)\b/i ``` Sources: [src/middleware/csrf/index.ts:28-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L28-L30), [src/middleware/csrf/index.ts:94-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L94-L150) ```typescript return async function csrf(c, next) { if ( !isSafeMethodRe.test(c.req.method) && isRequestedByFormElementRe.test(c.req.header('content-type') || 'text/plain') && !(await isAllowedSecFetchSite(c.req.header('sec-fetch-site'), c)) && !(await isAllowedOrigin(c.req.header('origin'), c)) ) { const res = new Response('Forbidden', { status: 403 }) throw new HTTPException(403, { res }) } await next() } ``` Sources: [src/middleware/csrf/index.ts:138-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L138-L150) > [!WARNING] > Requests lacking both `sec-fetch-site` and `origin` headers during mutating form submissions will fail validation because both `isAllowedSecFetchSite` and `isAllowedOrigin` return `false` when their respective headers are undefined. > Sources: [src/middleware/csrf/index.ts:106-112](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L106-L112), [src/middleware/csrf/index.ts:126-136](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L126-L136) ### Verification Call Chain The execution trace for Sec-Fetch-Site validation flows through distinct functions defined across the module. 1. `csrf` — Intercepts the request inside the returned middleware handler and invokes `isAllowedSecFetchSite` with the `sec-fetch-site` header[src/middleware/csrf/index.ts:138-142](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L138-L142). 2. `isAllowedSecFetchSite` — Checks whether the header value is defined and passes the type guard `isSecFetchSite` before calling the configured `secFetchSiteHandler`[src/middleware/csrf/index.ts:126-136](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L126-L136). 3. `isSecFetchSite` — Validates that the string matches one of the permitted union constants[src/middleware/csrf/index.ts:15-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L15-L16). ```mermaid sequenceDiagram participant CSRF as csrf participant IASFS as isAllowedSecFetchSite participant ISFS as isSecFetchSite CSRF->>IASFS: c.req.header('sec-fetch-site') IASFS->>ISFS: secFetchSite string ISFS-->>IASFS: boolean type guard result IASFS-->>CSRF: boolean validation outcome ``` Sources: [src/middleware/csrf/index.ts:15-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L15-L16), [src/middleware/csrf/index.ts:126-136](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L126-L136), [src/middleware/csrf/index.ts:138-142](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L138-L142) ### Permitted Sec-Fetch-Site Constants The module defines explicit runtime values and type constraints for browser-supplied `Sec-Fetch-Site` headers. | Constant Array / Type | Value | Meaning / Role | | :--- | :--- | :--- | | `secFetchSiteValues` | `'same-origin'` | Request originated from the same site and origin. | | `secFetchSiteValues` | `'same-site'` | Request originated from a different path on the same site. | | `secFetchSiteValues` | `'none'` | Request was triggered by a direct user interaction like bookmark navigation. | | `secFetchSiteValues` | `'cross-site'` | Request originated from a completely external domain. | ```typescript const secFetchSiteValues = ['same-origin', 'same-site', 'none', 'cross-site'] as const type SecFetchSite = (typeof secFetchSiteValues)[number] const isSecFetchSite = (value: string): value is SecFetchSite => (secFetchSiteValues as readonly string[]).includes(value) ``` Sources: [src/middleware/csrf/index.ts:12-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L12-L16) ## CSRF Origin Resolution and Custom Matchers ### Origin and Sec-Fetch-Site Matcher Resolution The CSRF middleware normalizes both `origin` and `secFetchSite` options during initialization through higher-order function factories. When `options.origin` is omitted, the default handler extracts the origin from the request URL using `new URL(c.req.url).origin`. If `options.origin` is provided as a string, it constructs an exact equality matcher. If it is an array, it evaluates membership using `optsOrigin.includes(origin)`. When supplied as a custom function, the middleware delegates directly to the user-defined handler callback. ```typescript const originHandler: IsAllowedOriginHandler = ((optsOrigin) => { if (!optsOrigin) { return (origin, c) => origin === new URL(c.req.url).origin } else if (typeof optsOrigin === 'string') { return (origin) => origin === optsOrigin } else if (typeof optsOrigin === 'function') { return optsOrigin } else { return (origin) => optsOrigin.includes(origin) } })(options?.origin) ``` Sources: [src/middleware/csrf/index.ts:95-105](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L95-L105) Similarly, `secFetchSiteHandler` builds its validation logic based on the input type of `options.secFetchSite`. If undefined, it restricts permitted traffic exclusively to `'same-origin'`. String, array, and function options follow identical resolution branches to evaluate browser metadata against configured rules. ```typescript const secFetchSiteHandler: IsAllowedSecFetchSiteHandler = ((optsSecFetchSite) => { if (!optsSecFetchSite) { // Default: only allow same-origin return (secFetchSite) => secFetchSite === 'same-origin' } else if (typeof optsSecFetchSite === 'string') { return (secFetchSite) => secFetchSite === optsSecFetchSite } else if (typeof optsSecFetchSite === 'function') { return optsSecFetchSite } else { return (secFetchSite) => optsSecFetchSite.includes(secFetchSite) } })(options?.secFetchSite) ``` Sources: [src/middleware/csrf/index.ts:114-125](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L114-L125) > [!NOTE] > If the `origin` header is entirely absent from the incoming request, `isAllowedOrigin` immediately short-circuits and returns `false` without invoking the underlying handler. > Sources: [src/middleware/csrf/index.ts:106-112](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L106-L112) ### Custom Matcher Signatures and Handlers Both `origin` and `secFetchSite` support asynchronous or synchronous custom handler functions that receive the header value alongside the active [execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context). These hooks allow developers to implement granular policies such as validating specific subdomain patterns or permitting cross-site requests exclusively for designated webhook endpoints. ```typescript export type IsAllowedOriginHandler = (origin: string, context: Context) => boolean | Promise export type IsAllowedSecFetchSiteHandler = ( secFetchSite: SecFetchSite, context: Context ) => boolean | Promise ``` ```typescript type IsAllowedOriginHandler = (origin: string, context: Context) => boolean | Promise const secFetchSiteValues = ['same-origin', 'same-site', 'none', 'cross-site'] as const type SecFetchSite = (typeof secFetchSiteValues)[number] const isSecFetchSite = (value: string): value is SecFetchSite => (secFetchSiteValues as readonly string[]).includes(value) type IsAllowedSecFetchSiteHandler = ( secFetchSite: SecFetchSite, context: Context ) => boolean | Promise ``` Sources: [src/middleware/csrf/index.ts:10-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L10-L21) > [!WARNING] > When `sec-fetch-site` contains an unrecognised string value not present in the runtime `secFetchSiteValues` tuple, `isSecFetchSite` evaluates to `false` and causes validation to fail before the custom `secFetchSiteHandler` can execute. > Sources: [src/middleware/csrf/index.ts:12-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L12-L16), [src/middleware/csrf/index.ts:131-135](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts#L131-L135) ## Body Limit Middleware and Stream Wrapping ### Public API Surface and Configuration Options The body limit middleware restricts incoming request payload sizes to protect applications against denial-of-service attacks [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) caused by oversized payloads. It exports a `bodyLimit` factory function that accepts a `BodyLimitOptions` configuration object specifying the `maxSize` threshold in bytes and an optional custom error handler function `onError`. | Option Property | Type | Default Behavior | Purpose | | :--- | :--- | :--- | :--- | | `maxSize` | `number` | *Required* | Maximum allowable body size in bytes. | | `onError` | `OnError` | Throws `HTTPException(413)` with text `'Payload Too Large'` | Handler invoked when `maxSize` is exceeded. | ```typescript type OnError = (c: Context) => Response | Promise type BodyLimitOptions = { maxSize: number onError?: OnError } ``` Sources: [src/middleware/body-limit/index.ts:12-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:12-16) ```typescript export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => { const onError: OnError = options.onError || (() => { const res = new Response(ERROR_MESSAGE, { status: 413, }) throw new HTTPException(413, { res }) }) const maxSize = options.maxSize ``` Sources: [src/middleware/body-limit/index.ts:50-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:50-59) > [!NOTE] > If `options.onError` is omitted, the default error handler constructs a standard Web `Response` with status code `413` and throws an `HTTPException`. > Sources: [src/middleware/body-limit/index.ts:51-58](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:51-58) ### Content-Length Pre-Checks and Chunk Tracking When an incoming request reaches the middleware, it first evaluates whether a request body exists. If `c.req.raw.body` is null or undefined (such as standard `GET` or `HEAD` requests), the middleware bypasses inspection and invokes `next()` immediately. ```typescript return async function bodyLimit(c, next) { if (!c.req.raw.body) { // maybe GET or HEAD request return next() } ``` Sources: [src/middleware/body-limit/index.ts:61-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:61-65) If headers contain a `content-length` without a `transfer-encoding` header, the middleware performs a fast pre-check by parsing the length directly. If `content-length` exceeds `maxSize`, it immediately invokes `onError(c)` without consuming the stream. ```typescript const hasTransferEncoding = c.req.raw.headers.has('transfer-encoding') const hasContentLength = c.req.raw.headers.has('content-length') if (hasContentLength && !hasTransferEncoding) { // Only Content-Length present - we can trust it const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10) return contentLength > maxSize ? onError(c) : next() } ``` Sources: [src/middleware/body-limit/index.ts:67-74](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:67-74) When `transfer-encoding` (chunked) is present or length headers are missing entirely, per RFC 7230, transfer-encoding takes precedence. The middleware consumes the underlying `ReadableStream` chunk by chunk using a `ReadableStreamDefaultReader`, accumulating byte lengths into a running `size` counter and pushing each `Uint8Array` chunk into an array. If accumulated size exceeds `maxSize` at any point during iteration, processing terminates instantly and invokes `onError(c)`. ```typescript // Transfer-Encoding present (chunked) or no length headers. // Per RFC 7230, when both are present Transfer-Encoding takes precedence // and Content-Length is ignored. Read the body up-front so the size check // is final before the handler runs, regardless of how (or whether) the // handler reads the body. let size = 0 const chunks: Uint8Array[] = [] const rawReader = c.req.raw.body.getReader() for (;;) { const { done, value } = await rawReader.read() if (done) { break } size += value.length if (size > maxSize) { return onError(c) } chunks.push(value) } ``` Sources: [src/middleware/body-limit/index.ts:76-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:76-94) > [!WARNING] > Because chunked or length-less streams are read entirely into memory arrays during validation, extremely large streaming payloads will consume memory proportional to their size up to the threshold before being rejected or forwarded. > Sources: [src/middleware/body-limit/index.ts:81-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:81-94) ### Streaming Body Reconstruction and Replacement Once a chunked or un-sized stream successfully passes the byte limit verification, the accumulated chunks must be restored so downstream route handlers and parsers can read the request body normally. The middleware constructs a fresh `ReadableStream` that enqueues the saved `Uint8Array` chunks in sequence and closes the controller. ```typescript const requestInit: RequestInit & { duplex: 'half' } = { body: new ReadableStream({ start(controller) { for (const chunk of chunks) { controller.enqueue(chunk) } controller.close() }, }), ``` Sources: [src/middleware/body-limit/index.ts:96-104](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:96-104) It then instantiates a new standard `Request` object wrapping the fresh readable stream with explicit `duplex: 'half'` options, assigns it back to `c.req.raw`, and proceeds down the middleware chain via `next()`. ```typescript duplex: 'half', } c.req.raw = new Request(c.req.raw, requestInit as RequestInit) ``` Sources: [src/middleware/body-limit/index.ts:105-108](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:105-108) ## Payload Overflow Detection and Error Handling ### Error Trigger Conditions and HTTPException 413 When the body limit middleware detects that a payload exceeds the configured `maxSize`, it immediately halts further stream consumption or execution and invokes the error handler. For requests governed by a trustworthy `content-length` header, this triggers as soon as `content-length > maxSize`. For chunked or un-sized streams, the check occurs incrementally during stream iteration inside the reader loop whenever the running `size` counter surpasses `maxSize`. ```typescript if (hasContentLength && !hasTransferEncoding) { // Only Content-Length present - we can trust it const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10) return contentLength > maxSize ? onError(c) : next() } ``` Sources: [src/middleware/body-limit/index.ts:70-74](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:70-74) ```typescript size += value.length if (size > maxSize) { return onError(c) } chunks.push(value) } ``` Sources: [src/middleware/body-limit/index.ts:89-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:89-94) > [!CAUTION] > When consuming chunked streams, the reader halts the moment `size > maxSize` is met mid-stream, preventing excess bytes from accumulating into memory while terminating the active request stream early. > Sources: [src/middleware/body-limit/index.ts:89-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:89-94) ### Custom onError Callbacks and Default Response Termination Developers can supply a custom `onError` callback function within `BodyLimitOptions` to customize how payload overflows are formatted and returned to clients. If `options.onError` is omitted, the middleware falls back to a default handler that instantiates a web standard `Response` using the constant `ERROR_MESSAGE` string (`'Payload Too Large'`) with status code `413`, and immediately throws an `HTTPException(413, { res })`. ```typescript const ERROR_MESSAGE = 'Payload Too Large' type OnError = (c: Context) => Response | Promise type BodyLimitOptions = { maxSize: number onError?: OnError } ``` Sources: [src/middleware/body-limit/index.ts:10-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:10-16) ```typescript export const bodyLimit = (options: BodyLimitOptions): MiddlewareHandler => { const onError: OnError = options.onError || (() => { const res = new Response(ERROR_MESSAGE, { status: 413, }) throw new HTTPException(413, { res }) }) ``` Sources: [src/middleware/body-limit/index.ts:50-58](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:50-58) ```typescript return contentLength > maxSize ? onError(c) : next() } ``` Sources: [src/middleware/body-limit/index.ts:73-74](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:73-74) ```typescript if (size > maxSize) { return onError(c) } ``` Sources: [src/middleware/body-limit/index.ts:90-92](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:90-92) > [!NOTE] > The `OnError` type signature specifies that custom handlers accept the active `Context` (`c`) and return either a `Response` or a `Promise`, allowing seamless integration with context response helpers like `c.text()`. > Sources: [src/middleware/body-limit/index.ts:12-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:12-16) ## Security Configuration and Defense in Depth ### Proxy Adapters and Edge Request Initialization When deploying security middleware like CSRF protection and body limits behind serverless runtimes or edge proxies, incoming event structures must be accurately transformed into web standard `Request` instances. Adapters such as `aws-lambda` and `lambda-edge` process incoming events by parsing HTTP headers, methods, query strings, and body payloads before dispatching them into Hono's `app.fetch()`. ```typescript const createRequest = (event: CloudFrontEdgeEvent): Request => { const queryString = event.Records[0].cf.request.querystring const host = event.Records[0].cf.request.headers?.host?.[0]?.value || event.Records[0].cf.config.distributionDomainName const urlPath = `https://${host}${event.Records[0].cf.request.uri}` const url = queryString ? `${urlPath}?${queryString}` : urlPath const headers = new Headers() Object.entries(event.Records[0].cf.request.headers).forEach(([k, v]) => { v.forEach((header) => headers.append(k, header.value)) }) const requestBody = event.Records[0].cf.request.body const method = event.Records[0].cf.request.method const rawBody = createBody(method, requestBody) let body: string | Uint8Array | undefined = rawBody if (rawBody !== undefined) { const bytes = typeof rawBody === 'string' ? (new TextEncoder().encode(rawBody) as Uint8Array) : rawBody body = bytes headers.set('content-length', bytes.length.toString()) } return new Request(url, { headers, method, body, }) } ``` Sources: [src/adapter/lambda-edge/handler.ts:152-184](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts:152-184) > [!IMPORTANT] > Edge adapters like Lambda@Edge manually assign content-length headers when request body bytes are present, ensuring downstream size validation and body limit middleware can inspect exact payload dimensions before handlers execute. > Sources: [src/adapter/lambda-edge/handler.ts:169-177](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts:169-177) ### Combining CSRF Protection and Body Constraints Layering both `csrf()` and `bodyLimit()` creates a multi-layered defense against malicious web requests. The CSRF middleware evaluates mutating HTTP methods against form element content-types (`application/x-www-form-urlencoded`, `multipart/form-data`, `text/plain`), requiring valid `sec-fetch-site` or `origin` validation headers before allowing execution to proceed. ```typescript return async function csrf(c, next) { if ( !isSafeMethodRe.test(c.req.method) && isRequestedByFormElementRe.test(c.req.header('content-type') || 'text/plain') && !(await isAllowedSecFetchSite(c.req.header('sec-fetch-site'), c)) && !(await isAllowedOrigin(c.req.header('origin'), c)) ) { const res = new Response('Forbidden', { status: 403 }) throw new HTTPException(403, { res }) } await next() } ``` Sources: [src/middleware/csrf/index.ts:138-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts:138-150) Once origin and site context validation pass, the body limit middleware intercepts incoming streams, enforcing strict `maxSize` thresholds to reject oversized payloads with an `HTTPException(413)` before memory exhaustion occurs. ```typescript return async function bodyLimit(c, next) { if (!c.req.raw.body) { // maybe GET or HEAD request return next() } const hasTransferEncoding = c.req.raw.headers.has('transfer-encoding') const hasContentLength = c.req.raw.headers.has('content-length') if (hasContentLength && !hasTransferEncoding) { // Only Content-Length present - we can trust it const contentLength = parseInt(c.req.raw.headers.get('content-length') || '0', 10) return contentLength > maxSize ? onError(c) : next() } ``` Sources: [src/middleware/body-limit/index.ts:61-74](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts:61-74) ## Related - [Secure Headers and CORS](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/secure-headers-and-cors) - [Basic and Bearer Auth](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/basic-and-bearer-auth) --- ## Technical docs: IP Restriction URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/ip-restriction
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/utils/ipaddr.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts) - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/adapter/vercel/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/conninfo.ts) - [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/adapter/lambda-edge/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts) - [src/adapter/bun/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts) - [src/validator/validator.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/validator/validator.ts) - [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts) - [src/adapter/aws-lambda/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/conninfo.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/adapter/cloudflare-workers/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/conninfo.ts) - [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts) - [src/adapter/netlify/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/conninfo.ts) - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/middleware/jwk/keys.test.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/keys.test.json) - [src/adapter/cloudflare-pages/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/conninfo.ts) - [src/helper/conninfo/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/conninfo/types.ts) - [src/utils/accept.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts) - [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts) - [src/utils/compress.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/compress.ts) - [src/adapter/deno/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts) - [src/utils/cookie.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/cookie.ts) - [src/helper/conninfo/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/conninfo/index.ts) - [src/router/reg-exp-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/node.ts) - [src/validator/utils.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/validator/utils.ts) - [src/utils/headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/headers.ts) - [src/middleware/secure-headers/permissions-policy.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/permissions-policy.ts)
## Overview The IP restriction middleware restricts incoming HTTP requests by evaluating client IP addresses against configurable allow and deny rules. It processes static IP addresses, CIDR notation subnets for both IPv4 and IPv6, wildcard patterns, and custom validation functions. Sources: [src/middleware/ip-restriction/index.ts:26-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L26-L38), [src/middleware/ip-restriction/index.ts:83-87](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L83-L87), [src/middleware/ip-restriction/index.ts:172-175](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L172-L175) Client addresses are retrieved via connection info helpers across multiple [runtime adapters](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/runtime-adapters/runtime-adapters) and normalized for comparison. The middleware converts dotted-decimal IPv4 and hexadecimal IPv6 addresses into bigint binary representations, handling IPv4-mapped IPv6 formats and subnet bitmasks for precise access control decisions. Sources: [src/middleware/ip-restriction/index.ts:10-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L10-L18), [src/middleware/ip-restriction/index.ts:104-114](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L104-L114), [src/middleware/ip-restriction/index.ts:131-139](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L131-L139) ## Middleware Configuration and Public Interface ### Public API Options and Types The IP restriction middleware accepts a connection retrieval function and an options object containing configuration lists. The public interface defines rules that support wildcard matching, static addresses, CIDR notation subnets, and predicate functions [src/middleware/ip-restriction/index.ts:23-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L23-L38), [src/middleware/ip-restriction/index.ts:172-183](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L172-L183). | Option / Type | Type Definition | Description | | :--- | :--- | :--- | | `GetIPAddr` | `GetConnInfo \| ((c: Context) => string)` | Function to retrieve the client IP address from context or connection info. | | `IPRestrictionRule` | `string \| ((addr: { addr: string; type: AddressType }) => boolean)` | Rule definition accepting a literal pattern, CIDR range, wildcard, or evaluation callback. | | `IPRestrictionRules` | `{ denyList?: IPRestrictionRule[]; allowList?: IPRestrictionRule[] }` | Container object holding optional deny and allow rule lists. | Sources: [src/middleware/ip-restriction/index.ts:23-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L23-L38), [src/middleware/ip-restriction/index.ts:172-183](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L172-L183) ### Rule Formats and Matcher Compilation Rule processing utilizes `buildMatcher` to compile rule arrays into optimized lookup sets and bitmasks [src/middleware/ip-restriction/index.ts:51-120](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L51-L120). The middleware evaluates incoming client requests against these compiled structures. > [!WARNING] > CIDR prefix validation strictly requires 1 to 3 decimal digits matching `/^[0-9]{1,3}$/` and throws a `TypeError` if the parsed integer exceeds 32 for IPv4 or 128 for IPv6 [src/middleware/ip-restriction/index.ts:41-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L41-L50), [src/middleware/ip-restriction/index.ts:98](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L98). Sources: [src/middleware/ip-restriction/index.ts:41-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L41-L50), [src/middleware/ip-restriction/index.ts:51-120](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L51-L120) ## Client IP Extraction Across Runtimes ### Connection Information Interface and Adapters Hono extracts remote client addresses through runtime-specific connection info helpers adhering to the `GetConnInfo` type signature. Each adapter accesses underlying request context properties or platform-specific headers to populate the `ConnInfo` structure containing remote address, address type, port, and transport protocol [src/helper/conninfo/types.ts:35-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/conninfo/types.ts#L35-L45). | Runtime / Adapter | Source Mechanism | Extracted Properties | | :--- | :--- | :--- | | **Bun** | `server.requestIP(c.req.raw)` | `address`, `addressType` (`IPv4` / `IPv6`), `port` [src/adapter/bun/conninfo.ts:11-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L11-L41) | | **Deno** | `c.env.remoteAddr` | `address` (`hostname`), `port`, `transport` [src/adapter/deno/conninfo.ts:9-15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts#L9-L15) | | **Cloudflare Workers** | `c.req.header('cf-connecting-ip')` | `address` via header [src/adapter/cloudflare-workers/conninfo.ts:3-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/conninfo.ts#L3-L6) | | **Cloudflare Pages** | `c.req.header('cf-connecting-ip')` | `address` via header [src/adapter/cloudflare-pages/conninfo.ts:22-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/conninfo.ts#L22-L25) | | **Vercel** | `c.req.header('x-real-ip')` | `address` via header [src/adapter/vercel/conninfo.ts:3-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/conninfo.ts#L3-L7) | | **Netlify** | `c.env.context?.ip` | `address` from Netlify function context [src/adapter/netlify/conninfo.ts:53-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/conninfo.ts#L53-L56) | | **AWS Lambda** | API Gateway v1/v2 or ALB `x-forwarded-for` | `address` from `requestContext.identity.sourceIp`, `requestContext.http.sourceIp`, or trailing XFF entry [src/adapter/aws-lambda/conninfo.ts:45-66](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/conninfo.ts#L45-L66) | | **Lambda@Edge** | `c.env.event.Records[0].cf.request.clientIp` | `address` from CloudFront event record [src/adapter/lambda-edge/conninfo.ts:11-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts#L11-L14) | Sources: [src/adapter/bun/conninfo.ts:11-41](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L11-L41), [src/adapter/deno/conninfo.ts:9-15](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/conninfo.ts#L9-L15), [src/adapter/cloudflare-workers/conninfo.ts:3-6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/conninfo.ts#L3-L6), [src/adapter/cloudflare-pages/conninfo.ts:22-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/conninfo.ts#L22-L25), [src/adapter/vercel/conninfo.ts:3-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/conninfo.ts#L3-L7), [src/adapter/netlify/conninfo.ts:53-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/conninfo.ts#L53-L56), [src/adapter/aws-lambda/conninfo.ts:45-66](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/conninfo.ts#L45-L66), [src/adapter/lambda-edge/conninfo.ts:11-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts#L11-L14) ### Specialized Adapter Extraction Behaviors AWS Lambda handles multiple event payload structures by checking `requestContext.identity` for API Gateway REST APIs, `requestContext.http` for HTTP APIs and Function URLs, and falling back to parsing the comma-separated `x-forwarded-for` header where Application Load Balancers append the client IP to the end [src/adapter/aws-lambda/conninfo.ts:50-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/conninfo.ts#L50-L65). Bun validates server existence and inspects `server.requestIP`, returning an empty remote object if the request is closed or uses a Unix domain socket [src/adapter/bun/conninfo.ts:19-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L19-L34). > [!CAUTION] > In Bun, if the server instance is missing from the environment or `server.requestIP` is not a function, a `TypeError` is thrown immediately during connection info resolution [src/adapter/bun/conninfo.ts:19-24](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L19-L24). Sources: [src/adapter/aws-lambda/conninfo.ts:50-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/conninfo.ts#L50-L65), [src/adapter/bun/conninfo.ts:19-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/conninfo.ts#L19-L34) ## IPv4 and Subnet Binary Conversion ### Dotted-Decimal Parsing and Bitwise Construction Dotted-decimal IPv4 strings are processed character by character using `parseIPv4ToBinary`, converting the string representation into a 32-bit unsigned integer represented as a `bigint`. The parser iterates through the specified string range, verifying character ASCII codes against digits (`0`-`9`), dots (`.`), and octet value bounds. ```typescript const parseIPv4ToBinary = ( ipv4: string, start: number, end: number, onInvalid: () => never ): bigint => { let result = 0n let octets = 0 let octet = 0 let digits = 0 let firstDigit = 0 for (let i = start; i <= end; i++) { const code = i < end ? ipv4.charCodeAt(i) : CHAR_CODE_DOT if (code >= CHAR_CODE_0 && code <= CHAR_CODE_9) { if (digits === 0) { firstDigit = code } else if (firstDigit === CHAR_CODE_0) { onInvalid() } octet = octet * 10 + code - CHAR_CODE_0 if (octet > 255) { onInvalid() } digits++ continue } if (code !== CHAR_CODE_DOT || digits === 0 || octets === 4) { onInvalid() } result = (result << 8n) + BigInt(octet) octets++ octet = 0 digits = 0 } if (octets !== 4) { onInvalid() } return result } ``` Sources: [src/utils/ipaddr.ts:83-126](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L83-L126) Leading zeros within an octet (other than a standalone `0`) trigger validation failures to prevent ambiguity. Each parsed octet is shifted left by 8 bits (`result = (result << 8n) + BigInt(octet)`) as the parser progresses across dots. > [!WARNING] > An octet value exceeding 255, failing to provide exactly four dot-separated octets, or containing leading zeros like `192.168.01.1` will immediately invoke the error handler and throw an invalid IP exception. Sources: [src/utils/ipaddr.ts:98-123](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L98-L123) ### CIDR Subnet Prefix Parsing and Bitmasks CIDR notation rules are parsed by matching expressions against `IS_CIDR_NOTATION_REGEX = /\/[^/]*$/`. The prefix length is extracted and validated against numeric constraints via `parseCidrPrefix`, ensuring the prefix integer does not exceed 32 for IPv4 rules. ```typescript const IS_CIDR_NOTATION_REGEX = /\/[^/]*$/ const parseCidrPrefix = (rule: string, prefix: string, max: number): number => { if (!/^[0-9]{1,3}$/.test(prefix)) { throw new TypeError(`Invalid rule: ${rule}`) } const parsedPrefix = parseInt(prefix) if (parsedPrefix > max) { throw new TypeError(`Invalid rule: ${rule}`) } return parsedPrefix } ``` Sources: [src/middleware/ip-restriction/index.ts:40-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L40-L50) Once the prefix is verified, a bitmask is generated using bitwise shift operators. For an IPv4 CIDR range, the mask is constructed by shifting `1n` left by the prefix length, subtracting `1n`, and left-shifting the result by `32 - prefix`. ```typescript const mask = ((1n << BigInt(prefix)) - 1n) << BigInt((isIPv4 ? 32 : 128) - prefix) cidrRules.push([isIPv4, addr & mask, mask] as [boolean, bigint, bigint]) ``` Sources: [src/middleware/ip-restriction/index.ts:111-113](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L111-L113) ### Execution Walkthrough and Sequence When static rules or CIDR rules are compiled, IP strings pass through a deterministic function chain. 1. `registerStaticRule` receives an IP rule string and invokes `distinctRemoteAddr` to classify it [src/middleware/ip-restriction/index.ts:59-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L59-L64). 2. `convertIPv4ToBinary` is called for IPv4 addresses to parse the dotted-decimal string [src/middleware/ip-restriction/index.ts:65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L65). 3. `throwInvalidIPv4Address` is invoked if parsing encounters malformed octets [src/utils/ipaddr.ts:148-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L148-L150). 4. `createInvalidIPAddressError` generates the typed `TypeError` object carrying `ERR_INVALID_IP_ADDRESS` [src/utils/ipaddr.ts:69-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L69-L73). Sources: [src/middleware/ip-restriction/index.ts:59-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L59-L65), [src/utils/ipaddr.ts:69-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L69-L73), [src/utils/ipaddr.ts:148-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L148-L150) ```mermaid sequenceDiagram participant Index as ip-restriction/index.ts participant IpAddr as utils/ipaddr.ts Index->>IpAddr: registerStaticRule() calls convertIPv4ToBinary() IpAddr->>IpAddr: parseIPv4ToBinary() validates octets IpAddr->>IpAddr: throwInvalidIPv4Address() on malformed input IpAddr->>IpAddr: createInvalidIPAddressError() instantiates ERR_INVALID_IP_ADDRESS ``` Sources: [src/middleware/ip-restriction/index.ts:59-65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L59-L65), [src/utils/ipaddr.ts:69-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L69-L77), [src/utils/ipaddr.ts:148-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L148-L150) ## IPv6 Address Normalization and Expansion ### Zero-Compression and Section Expansion Shortened IPv6 addresses containing double colons (`::`) are expanded to their full canonical 8-section representation by `expandIPv6`. The input string is first split by colons, and if the final section matches an IPv4 format via `IPV4_REGEX`, it is converted to binary and mapped back into hexadecimal IPv6 sections. ```typescript export const expandIPv6 = (ipV6: string): string => { const sections = ipV6.split(':') if (IPV4_REGEX.test(sections.at(-1) as string)) { sections.splice( -1, 1, ...convertIPv6BinaryToString(convertIPv4ToBinary(sections.at(-1) as string)) // => ::7f00:0001 .substring(2) // => 7f00:0001 .split(':') // => ['7f00', '0001'] ) } ``` Sources: [src/utils/ipaddr.ts:13-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L13-L23) The function iterates through each section, padding non-empty nodes to four characters with leading zeros. When an empty string slot is encountered from zero compression, subsequent empty sections are spliced out, and the single slot is replaced with enough `'0000'` blocks to ensure the final array reaches exactly eight sections. ```typescript for (let i = 0; i < sections.length; i++) { const node = sections[i] if (node !== '') { sections[i] = node.padStart(4, '0') } else { // Keep a single empty slot for `::` zero expansion. while (sections[i + 1] === '') { sections.splice(i + 1, 1) } sections[i] = new Array(8 - sections.length + 1).fill('0000').join(':') } } return sections.join(':') } ``` Sources: [src/utils/ipaddr.ts:24-37](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L24-L37) > [!NOTE] > The zero-expansion block calculates missing segments dynamically using `8 - sections.length + 1`, inserting the correct number of zero blocks to maintain standard IPv6 length compliance. Sources: [src/utils/ipaddr.ts:33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L33) ### Execution Walkthrough and Sequence When expanding and validating malformed addresses, execution proceeds through a strict error-handling call chain. 1. `expandIPv6` receives a shortened IPv6 address string and delegates nested IPv4-embedded segments to `convertIPv4ToBinary` [src/utils/ipaddr.ts:13-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L13-L19). 2. `convertIPv4ToBinary` parses the trailing IPv4 portion and invokes `throwInvalidIPv4Address` if octet bounds or formatting fail [src/utils/ipaddr.ts:148-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L148-L150). 3. `throwInvalidIPv4Address` immediately calls `createInvalidIPAddressError` with a formatted message [src/utils/ipaddr.ts:75-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L75-L77). 4. `createInvalidIPAddressError` instantiates the typed `TypeError` with error code `ERR_INVALID_IP_ADDRESS` [src/utils/ipaddr.ts:69-73](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L69-L73). Sources: [src/utils/ipaddr.ts:13-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L13-L19), [src/utils/ipaddr.ts:69-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L69-L77), [src/utils/ipaddr.ts:148-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L148-L150) ```mermaid sequenceDiagram participant IpAddr as utils/ipaddr.ts IpAddr->>IpAddr: expandIPv6() processes sections and checks trailing IPv4 IpAddr->>IpAddr: convertIPv4ToBinary() parses embedded IPv4 IpAddr->>IpAddr: throwInvalidIPv4Address() triggers on invalid octets IpAddr->>IpAddr: createInvalidIPAddressError() instantiates ERR_INVALID_IP_ADDRESS error ``` Sources: [src/utils/ipaddr.ts:13-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L13-L19), [src/utils/ipaddr.ts:69-77](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L69-L77), [src/utils/ipaddr.ts:148-150](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/ipaddr.ts#L148-L150) ## Subnet Matching and Decision Evaluation ### CIDR Rule Compilation and Mask Generation The `buildMatcher` function processes configured IP rules to construct high-performance lookup structures. When a rule contains CIDR notation detected by `IS_CIDR_NOTATION_REGEX`, the prefix length is validated using `parseCidrPrefix`, ensuring it does not exceed 32 for IPv4 or 128 for IPv6. If the parsed prefix equals the maximum bit length, the rule is treated as a static address and registered directly. ```typescript const IS_CIDR_NOTATION_REGEX = /\/[^/]*$/ const parseCidrPrefix = (rule: string, prefix: string, max: number): number => { if (!/^[0-9]{1,3}$/.test(prefix)) { throw new TypeError(`Invalid rule: ${rule}`) } const parsedPrefix = parseInt(prefix) if (parsedPrefix > max) { throw new TypeError(`Invalid rule: ${rule}`) } return parsedPrefix } ``` Sources: [src/middleware/ip-restriction/index.ts:40-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L40-L50) For subnet ranges, bitmasks are computed using BigInt shift operations. When an IPv6 rule represents an IPv4-mapped address with a prefix of 96 or greater, the rule is normalized into an IPv4 CIDR range by subtracting 96 from the prefix length. ```typescript if (IS_CIDR_NOTATION_REGEX.test(rule)) { const separatedRule = rule.split('/') const addrStr = separatedRule[0] const type = distinctRemoteAddr(addrStr) if (type === undefined) { throw new TypeError(`Invalid rule: ${rule}`) } let isIPv4 = type === 'IPv4' let prefix = parseCidrPrefix(rule, separatedRule[1], isIPv4 ? 32 : 128) if (isIPv4 ? prefix === 32 : prefix === 128) { // this rule is a static rule rule = addrStr } else { let addr = (isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary)(addrStr) if (type === 'IPv6' && isIPv4MappedIPv6(addr) && prefix >= 96) { isIPv4 = true addr = convertIPv4MappedIPv6ToIPv4(addr) prefix -= 96 } const mask = ((1n << BigInt(prefix)) - 1n) << BigInt((isIPv4 ? 32 : 128) - prefix) cidrRules.push([isIPv4, addr & mask, mask] as [boolean, bigint, bigint]) continue } ``` Sources: [src/middleware/ip-restriction/index.ts:88-115](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L88-L115) > [!WARNING] > IPv4-mapped IPv6 CIDR rules with prefixes under 96 bits are evaluated under IPv6 rules, whereas prefixes of 96 bits or greater are shifted down and evaluated as IPv4 ranges to maintain correct binary mask alignment. Sources: [src/middleware/ip-restriction/index.ts:105-109](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L105-L109) ### Evaluation Logic and Runtime Matching The returned matcher evaluates incoming remote connection objects against compiled static sets, CIDR bitmasks, and custom callback functions in a sequential evaluation chain. ```typescript return (remote: { addr: string type: AddressType isIPv4: boolean binaryAddr?: bigint }): boolean => { if (staticRules.has(remote.addr)) { return true } const remoteAddr = (remote.binaryAddr ||= ( remote.isIPv4 ? convertIPv4ToBinary : convertIPv6ToBinary )(remote.addr)) const remoteIPv4Addr = remote.isIPv4 || isIPv4MappedIPv6(remoteAddr) ? remote.isIPv4 ? remoteAddr : convertIPv4MappedIPv6ToIPv4(remoteAddr) : undefined if ((remote.isIPv4 ? staticIPv4Rules : staticIPv6Rules).has(remoteAddr)) { return true } for (const [isIPv4, addr, mask] of cidrRules) { if (isIPv4) { if (remoteIPv4Addr === undefined) { continue } if ((remoteIPv4Addr & mask) === addr) { return true } continue } if (remote.isIPv4) { continue } if ((remoteAddr & mask) === addr) { return true } } for (const rule of functionRules) { if (rule({ addr: remote.addr, type: remote.type })) { return true } } return false } ``` Sources: [src/middleware/ip-restriction/index.ts:122-166](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L122-L166) | Lookup Target | Internal Structure | Matching Mechanism | | :--- | :--- | :--- | | Static String | `staticRules` (`Set`) | Direct string hash lookup against `remote.addr` | | Static Binary IPv4 | `staticIPv4Rules` (`Set`) | BigInt lookup using `convertIPv4ToBinary` | | Static Binary IPv6 | `staticIPv6Rules` (`Set`) | BigInt lookup using `convertIPv6ToBinary` | | CIDR Subnets | `cidrRules` (`[boolean, bigint, bigint][]`) | Bitwise AND evaluation: `(remoteAddr & mask) === addr` | | Custom Functions | `functionRules` (`IPRestrictionRuleFunction[]`) | Iterative execution of user-supplied predicate functions | Sources: [src/middleware/ip-restriction/index.ts:54-58](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L54-L58), [src/middleware/ip-restriction/index.ts:128-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L128-L164) > [!TIP] > Remote binary addresses are lazily evaluated and cached on the `remote` context object using logical assignment (`remote.binaryAddr ||= ...`), avoiding redundant string-to-bigint parsing during repeated middleware evaluations. Sources: [src/middleware/ip-restriction/index.ts:131-133](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L131-L133) ## Rejection Handling and Custom Responses ### Execution Flow and Denial Enforcement When the IP restriction middleware processes an incoming request, access decisions are determined by evaluating the client's address against configured `denyList` and `allowList` rules. If a `denyList` is provided and the client IP matches any rule within it, or if an `allowList` is provided and the client IP fails to match any rule within it, access is denied and an `HTTPException` with status code `403` is thrown. ```typescript * * @example * ```ts * import { Hono } from 'hono' * import { ipRestriction } from 'hono/ip-restriction' * import { getConnInfo } from 'hono/cloudflare-workers' * * const app = new Hono() * * app.use( * '*', * ipRestriction(getConnInfo, { * // Block a specific IP and an entire subnet * denyList: ['192.168.0.5', '10.0.0.0/8'], * // Only allow requests from localhost and a private range * allowList: ['127.0.0.1', '::1', '192.168.1.0/24'], * }) * ) * * // With a custom error handler * app.use( * '/admin/*', * ipRestriction( * getConnInfo, * { allowList: ['203.0.113.0/24'] }, * (remote, c) => c.text(`Access denied for ${remote.addr}`, 403) * ) * ) * * app.get('/', (c) => c.text('Hello!')) * ``` ``` Sources: [src/middleware/ip-restriction/index.ts:186-216](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L186-L216) ```mermaid flowchart TD Start([Incoming Request]) --> GetIP[Extract Client IP via getIP] GetIP --> CheckDeny{DenyList Match?} CheckDeny -->|Yes| Throw403[Throw HTTPException 403] CheckDeny -->|No| CheckAllow{AllowList Provided?} CheckAllow -->|Yes| CheckAllowMatch{AllowList Match?} CheckAllowMatch -->|No| Throw403 CheckAllowMatch -->|Yes| Proceed["Call next()"] CheckAllow -->|No| Proceed ``` Sources: [src/middleware/ip-restriction/index.ts:186-216](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L186-L216) > [!WARNING] > If both a `denyList` and an `allowList` are configured, the `denyList` is evaluated first. A match in the deny list immediately triggers a `403` denial before the allow list is even checked. Sources: [src/middleware/ip-restriction/index.ts:188-198](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L188-L198) ### Custom Block Responses and Error Handling Developers can customize the response returned upon access denial by catching the `HTTPException` globally in Hono using `app.onError()`. Because the middleware relies on `HTTPException` from `../../http-exception`, catching status `403` allows applications to return custom JSON payloads, HTML error pages, or plain text messages instead of the default framework error response. ```typescript import { HTTPException } from '../../http-exception' ``` Sources: [src/middleware/ip-restriction/index.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L8) > [!TIP] > To supply a custom block response body, handle `HTTPException` in your Hono application error handler and check `err.status === 403` to render a tailored rejection message. Sources: [src/middleware/ip-restriction/index.ts:8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts#L8) ## Related - [Secure Headers and CORS](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/security-middleware/secure-headers-and-cors) --- ## Technical docs: ETag and Cache URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/etag-and-cache
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/etag/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts) - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/middleware/etag/digest.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts) - [src/utils/crypto.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/crypto.ts) - [src/middleware/bearer-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/bearer-auth/index.ts) - [src/middleware/compress/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/middleware/basic-auth/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/basic-auth/index.ts) - [src/middleware/timing/timing.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts) - [src/jsx/dom/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts) - [src/middleware/method-override/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts) - [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts) - [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts) - [src/middleware/jwk/keys.test.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwk/keys.test.json) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/helper/ssg/middleware.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/middleware.ts) - [src/middleware/cors/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cors/index.ts) - [src/adapter/cloudflare-workers/serve-static.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/serve-static.ts) - [src/utils/compress.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/compress.ts) - [src/middleware/request-id/request-id.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts) - [src/utils/headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/headers.ts) - [src/utils/buffer.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/buffer.ts) - [src/middleware/powered-by/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/powered-by/index.ts)
## Overview Hono provides robust ETag and Cache middleware features that optimize HTTP request-response lifecycles through automated cryptographic hashing, conditional validation, and Web Standard Cache API integration. By computing SHA-1 or custom digests from response streams, the ETag middleware evaluates `If-None-Match` headers against strong or weak tags to short-circuit redundant transmissions with `304 Not Modified` responses while retaining specified headers. Concurrently, the cache middleware interfaces with runtime storage via `caches.open` and `cache.match`, enforcing status code constraints, vary directive checks, and `Cache-Control` directives to manage cache population and conditional execution. Sources: [src/middleware/etag/index.ts:21-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L21-L36), [src/middleware/etag/index.ts:79-123](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L79-L123), [src/middleware/cache/index.ts:13-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L13-L35), [src/middleware/cache/index.ts:64-180](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L64-L180) ## ETag generation and hashing algorithms ### Public API and Generator Initialization The ETag middleware accepts an `ETagOptions` configuration object defining parameters that control tag formatting, retained headers on validation bypass, and custom hashing logic. When no custom generator is provided via `options.generateDigest`, the initializer falls back to the native `crypto.subtle` API using the `SHA-1` algorithm. | Option | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `retainedHeaders` | `string[]` | `RETAINED_304_HEADERS` | Headers preserved on `304 Not Modified` responses. | | `weak` | `boolean` | `false` | Prepends `W/` to generated ETags for weak validation. | | `generateDigest` | `(body: Uint8Array) => ArrayBuffer \| Promise` | `crypto.subtle` (SHA-1) | Custom digest generation function for response bodies. | Sources: [src/middleware/etag/index.ts:9-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L9-L13), [src/middleware/etag/index.ts:38-54](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L38-L54), [src/middleware/etag/index.ts:79-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L79-L82) ### Digest Calculation and Hex Encoding The `generateDigest` function reads response bodies iteratively via a `ReadableStream` reader, merging incoming chunks and invoking the digest generator. Once the stream is fully consumed, the resulting `ArrayBuffer` digest is converted into a lowercase hexadecimal string by mapping each byte to a zero-padded two-character hex value. ```typescript export const generateDigest = async ( stream: ReadableStream> | null, generator: (body: Uint8Array) => ArrayBuffer | Promise ): Promise => { if (!stream) { return null } let result: ArrayBuffer | undefined = undefined const reader = stream.getReader() for (;;) { const { value, done } = await reader.read() if (done) { break } result = await generator(mergeBuffers(result, value)) } if (!result) { return null } return Array.prototype.map .call(new Uint8Array(result), (x) => x.toString(16).padStart(2, '0')) .join('') } ``` Sources: [src/middleware/etag/digest.ts:16-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts#L16-L43) > [!NOTE] > If a response carries an existing `ETag` header from upstream handlers, the ETag middleware bypasses automatic digest calculation entirely and uses the pre-existing tag value. Sources: [src/middleware/etag/index.ts:90-95](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L90-L95) ## Conditional validation and weak tags ### Execution Walkthrough and Sequence Analysis Conditional validation in the ETag middleware evaluates incoming `If-None-Match` request headers against computed or pre-existing entity tags. When a request includes an `If-None-Match` header, the middleware inspects the value after downstream handlers execute and the response ETag is resolved. The validation check executes through a strict function call chain: `etag` handler invokes `etagMatches`, which in turn applies `stripWeak` to parse and normalize tags. ```mermaid sequenceDiagram participant Middleware as etag (index.ts) participant Matcher as etagMatches (index.ts) participant Stripper as stripWeak (index.ts) Middleware->>Matcher: etagMatches(etag, ifNoneMatch) Matcher->>Stripper: stripWeak(t) for each comma-split token Stripper-->>Matcher: normalized token string Matcher->>Stripper: stripWeak(etag) Stripper-->>Matcher: normalized etag string Matcher-->>Middleware: boolean match result ``` The execution sequence follows this precise path: 1. `etag` — The main middleware function extracts the `If-None-Match` request header and awaits downstream execution before reading the `ETag` response header or generating a fresh digest. Sources: [src/middleware/etag/index.ts:84-105](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L84-L105) 2. `etagMatches` — Evaluates whether `ifNoneMatch` is non-null, splits the header value by commas and optional whitespace (`/,\s*/`), and checks if any token matches the target ETag. Sources: [src/middleware/etag/index.ts:32-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L32-L36) 3. `stripWeak` — Strips the weak validation prefix `W/` from the beginning of a tag string using a regular expression replacement (`tag.replace(/^W\//, '')`), allowing weak and strong tags to be compared equivalently during validation. Sources: [src/middleware/etag/index.ts:30-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L30-L30) ### 304 Response Generation and Retained Headers When `etagMatches` returns true, the middleware short-circuits the response by constructing a new `304 Not Modified` response instance. This response discards the response body while preserving specific metadata headers defined by `retainedHeaders`. By default, the middleware references `RETAINED_304_HEADERS` to determine which response headers survive the validation bypass. | Header Constant | Value / Identifier | Purpose | | :--- | :--- | :--- | | `RETAINED_304_HEADERS` | `'cache-control'` | Retains caching directives on 304 responses. | | `RETAINED_304_HEADERS` | `'content-location'` | Retains resource location metadata. | | `RETAINED_304_HEADERS` | `'date'` | Retains server response timestamp. | | `RETAINED_304_HEADERS` | `'etag'` | Retains the entity tag for validation tracking. | | `RETAINED_304_HEADERS` | `'expires'` | Retains expiration time limits. | | `RETAINED_304_HEADERS` | `'vary'` | Retains cache negotiation criteria. | Sources: [src/middleware/etag/index.ts:21-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L21-L28), [src/middleware/etag/index.ts:107-119](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L107-L119) > [!NOTE] > When iterating over response headers during a 304 short-circuit, header keys are converted to lowercase via `key.toLowerCase()` before checking against the `retainedHeaders` index array, ensuring case-insensitive header preservation. Sources: [src/middleware/etag/index.ts:115-119](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts#L115-L119) ## Cache middleware and storage adapter ### Cache Storage Initialization and Availability Check The cache middleware integrates with the Web Standard `Cache API` via `globalThis.caches`. Upon initialization, the `cache` function verifies if `globalThis.caches` is defined in the current runtime. If the storage adapter is unavailable, the middleware checks the `onCacheNotAvailable` option: when set to `false`, it silently suppresses logging; when provided as a custom function, it invokes that handler; otherwise, it logs a default message to the console and returns a pass-through middleware handler that immediately invokes `next()`. ```typescript if (!globalThis.caches) { if (options.onCacheNotAvailable === false) { // suppress log } else if (options.onCacheNotAvailable) { options.onCacheNotAvailable() } else { console.log('Cache Middleware is not enabled because caches is not defined.') } return async (_c, next) => await next() } ``` Sources: [src/middleware/cache/index.ts:73-82](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L73-L82) When `globalThis.caches` is present, the middleware resolves the cache store name. The `cacheName` option accepts either a static string or a dynamic function `(c: Context) => Promise | string`. The resolved store name is passed to `caches.open(cacheName)` to obtain the cache instance. ```typescript const cacheName = typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName const cache = await caches.open(cacheName) ``` Sources: [src/middleware/cache/index.ts:155-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L155-L157) ### Request Matching and Key Generation Lifecycle Before executing downstream handlers, the middleware intercepts incoming requests. Requests are filtered by method and authorization headers: non-`GET` requests or requests containing an `Authorization` header bypass the cache middleware entirely and proceed directly to `next()`. ```typescript if (c.req.method !== 'GET' || c.req.raw.headers.has('Authorization')) { await next() return } ``` Sources: [src/middleware/cache/index.ts:139-142](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L139-L142) For valid `GET` requests, the cache key is constructed starting from the request URL (`c.req.url`). If a custom `keyGenerator` option is supplied, it executes to replace the base key string. When `vary` directives are configured, the middleware appends each specified header name and its URI-encoded request header value to the cache key using a double-colon delimiter format: `::directive=encodedValue`. ```typescript let key = c.req.url if (options.keyGenerator) { key = await options.keyGenerator(c) } if (varyDirectives) { for (const directive of varyDirectives) { const value = c.req.raw.headers.get(directive) ?? '' key += `::${directive}=${encodeURIComponent(value)}` } } ``` Sources: [src/middleware/cache/index.ts:144-153](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L144-L153) Once the cache key is assembled, the middleware queries the storage adapter via `cache.match(key)`. If a matching response is located, a new `Response` is instantiated from the cached response body and headers, short-circuiting further request execution and returning immediately. ```typescript const response = await cache.match(key) if (response) { return new Response(response.body, response) } ``` Sources: [src/middleware/cache/index.ts:158-161](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L158-L161) > [!WARNING] > Requests bearing an `Authorization` header automatically bypass the cache lookup and storage lifecycle, preventing authenticated user data from being improperly stored in shared cache tiers. Sources: [src/middleware/cache/index.ts:139-142](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L139-L142) ### Writing to the Cache Store When a cache miss occurs, the middleware awaits downstream execution (`await next()`). It then verifies whether the resulting response status code is present in the allowed `cacheableStatusCodes` set (which defaults to `[200]`). If the status code is ineligible, the middleware returns without caching. ```typescript await next() if (!cacheableStatusCodes.has(c.res.status)) { return } ``` Sources: [src/middleware/cache/index.ts:163-166](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L163-L166) Eligible responses undergo header augmentation and skip-cache evaluations. If checks pass, the response is cloned via `c.res.clone()`. The write operation to the cache store is governed by the `wait` boolean option: - When `wait` is set to `true`, Hono awaits the resolution of `cache.put(key, res)` before finishing the middleware handler execution (a requirement for runtimes like Deno). - When `wait` is `false` (the default), the promise returned by `cache.put(key, res)` is passed to `c.executionCtx.waitUntil()` to allow background storage without blocking the response delivery. ```typescript const res = c.res.clone() if (options.wait) { await cache.put(key, res) } else { c.executionCtx.waitUntil(cache.put(key, res)) } ``` Sources: [src/middleware/cache/index.ts:174-179](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L174-L179) > [!NOTE] > The `wait` option defaults to `false`. Explicitly setting `wait: true` is mandatory in Deno and other runtime environments that require pending promises to resolve within the request scope before termination. Sources: [src/middleware/cache/index.ts:44-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L44-L44), [src/middleware/cache/index.ts:84-86](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L84-L86) ## Cache control and skipping heuristics ### Heuristics and Skip Inspection The cache middleware evaluates several inspection rules before deciding whether an eligible response should be stored in the cache. These heuristics examine the `Cache-Control` header, `Set-Cookie` headers, and `Vary` directives to prevent writing private or sensitive data. ```typescript const shouldSkipCacheControl = (cacheControl: string | null): boolean => !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl) ``` Sources: [src/middleware/cache/index.ts:15-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L15-L16) The `shouldSkipCache` function consolidates these checks, returning `true` if any skipping criterion is satisfied: ```typescript const shouldSkipCache = ( res: Response, optionsVaryDirectives: Set | undefined, responseVary: string[] ): boolean => (responseVary.length && (!optionsVaryDirectives || responseVary.some((name) => !optionsVaryDirectives.has(name)))) || shouldSkipCacheControl(res.headers.get('Cache-Control')) || res.headers.has('Set-Cookie') ``` Sources: [src/middleware/cache/index.ts:27-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L27-L35) > [!WARNING] > Responses containing a `Set-Cookie` header or a `Cache-Control` directive matching `private`, `no-store`, or `no-cache` are automatically excluded from cache writes to prevent leaking user sessions or private records. > Sources: [src/middleware/cache/index.ts:32-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L32-L35) ### Skip Inspection Call Chain When determining whether to skip caching a response after downstream execution, Hono invokes a dedicated evaluation sequence. ```mermaid sequenceDiagram participant Index as src/middleware/cache/index.ts Index->>Index: cache(c, next) Index->>Index: shouldSkipCache(res, optionsVaryDirectives, responseVary) Index->>Index: shouldSkipCacheControl(cacheControl) ``` Sources: [src/middleware/cache/index.ts:15-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L15-L17), [src/middleware/cache/index.ts:27-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L27-L35), [src/middleware/cache/index.ts:170-172](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L170-L172) 1. `cache` invokes `shouldSkipCache` passing the response and vary directives. 2. `shouldSkipCache` checks vary conditions and calls `shouldSkipCacheControl`. 3. `shouldSkipCacheControl` tests the `Cache-Control` header string against the regex pattern for `private`, `no-store`, or `no-cache`. Sources: [src/middleware/cache/index.ts:15-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L15-L17), [src/middleware/cache/index.ts:27-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L27-L35), [src/middleware/cache/index.ts:170-172](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L170-L172) ### Header Augmentation Options The middleware can inject configured `Cache-Control` and `Vary` headers into outgoing responses prior to storage evaluation via the internal `addHeader` function. ```typescript const addHeader = (c: Context, responseVary: string[]) => { if (cacheControlDirectives) { const existingDirectives = c.res.headers .get('Cache-Control') ?.split(',') .map((d) => d.trim().split('=', 1)[0]) ?? [] for (const directive of cacheControlDirectives) { let [name, value] = directive.trim().split('=', 2) name = name.toLowerCase() if (!existingDirectives.includes(name)) { c.header('Cache-Control', `${name}${value ? `=${value}` : ''}`, { append: true }) } } } if (varyDirectives) { if (responseVary.length === 0) { c.header('Vary', Array.from(varyDirectives).join(', ')) } else { const merged = new Set(varyDirectives) for (const directive of responseVary) { merged.add(directive) } if (merged.has('*')) { c.header('Vary', '*') } else { c.header('Vary', Array.from(merged).join(', ')) } } } } ``` Sources: [src/middleware/cache/index.ts:105-136](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L105-L136) > [!NOTE] > If `varyDirectives` includes the wildcard token `*`, the middleware throws an error upon initialization because RFC 7231 Section 7.1.4 disallows effective caching when `*` is specified in the `Vary` header. > Sources: [src/middleware/cache/index.ts:93-99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts#L93-L99) ## Buffer management for digest hashing ### Chunk Concatenation and Memory Merging The `generateDigest` utility in `src/middleware/etag/digest.ts` processes streamed response payloads by reading chunks iteratively from a `ReadableStream>`. When building the complete hash input across multiple chunks, the internal `mergeBuffers` function combines an existing `ArrayBuffer` with an incoming `Uint8Array` chunk. If `buffer1` is undefined, it returns `buffer2` directly; otherwise, it allocates a new `ArrayBuffer` matching the combined byte lengths, writes the initial buffer at offset `0`, and copies the incoming chunk at offset `buffer1.byteLength`. ```typescript const mergeBuffers = ( buffer1: ArrayBuffer | undefined, buffer2: Uint8Array ): Uint8Array => { if (!buffer1) { return buffer2 } const merged = new Uint8Array( new ArrayBuffer(buffer1.byteLength + buffer2.byteLength) ) merged.set(new Uint8Array(buffer1), 0) merged.set(buffer2, buffer1.byteLength) return merged } ``` Sources: [src/middleware/etag/digest.ts:1-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts#L1-L14) > [!NOTE] > Successive chunks from the stream reader are accumulated iteratively via `mergeBuffers`, feeding the result into the custom or default `generator` function on every read cycle until the stream signals completion. > Sources: [src/middleware/etag/digest.ts:26-34](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts#L26-L34) ### Stream Reader Loop and Hex Encoding Once all stream chunks are processed and hashed, the resulting `ArrayBuffer` is converted into a lowercase hexadecimal string by mapping over its bytes with `toString(16).padStart(2, '0')` and joining them. If the input stream is null or yields no result, the generator returns `null`. ```typescript export const generateDigest = async ( stream: ReadableStream> | null, generator: (body: Uint8Array) => ArrayBuffer | Promise ): Promise => { if (!stream) { return null } let result: ArrayBuffer | undefined = undefined const reader = stream.getReader() for (;;) { const { value, done } = await reader.read() if (done) { break } result = await generator(mergeBuffers(result, value)) } if (!result) { return null } return Array.prototype.map .call(new Uint8Array(result), (x) => x.toString(16).padStart(2, '0')) .join('') } ``` Sources: [src/middleware/etag/digest.ts:16-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts#L16-L43) ## Related - [Response Compression](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/response-compression) - [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle) --- ## Technical docs: Response Compression URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/response-compression
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/compress/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts) - [src/middleware/etag/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts) - [src/jsx/streaming.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts) - [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/utils/compress.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/compress.ts) - [src/middleware/etag/digest.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts) - [src/helper/ssg/ssg.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/ssg.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/helper/proxy/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/proxy/index.ts) - [src/adapter/deno/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/deno/websocket.ts) - [src/utils/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/stream.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/middleware/serve-static/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/serve-static/index.ts) - [src/middleware/body-limit/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/body-limit/index.ts) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/adapter/bun/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/websocket.ts) - [src/middleware/timing/timing.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/client/fetch-result-please.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/client/fetch-result-please.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/adapter/cloudflare-workers/websocket.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/websocket.ts) - [runtime-tests/lambda/stream-mock.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/lambda/stream-mock.ts) - [src/helper/websocket/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/websocket/index.ts) - [src/utils/accept.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts)
## Overview Hono provides built-in response compression via the `compress` middleware, allowing applications to reduce network payload sizes by applying compression algorithms such as `gzip` and `deflate`. The middleware intercepts outgoing responses after route execution, evaluates criteria such as content length thresholds, content types, and caching directives, and transforms qualifying response streams using the Web Standard `CompressionStream` API. Sources: [src/middleware/compress/index.ts:46-121](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L46-L121) ## Middleware registration and configuration options The `compress` middleware is configured through the `CompressionOptions` interface, which defines parameters controlling encoding selection, minimum payload size thresholds, and content type filtering. When invoked via `compress(options)`, it returns a `MiddlewareHandler` that intercepts execution and inspects response characteristics. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `encoding` | `'gzip' \| 'deflate'` | `undefined` | The compression scheme to allow. If omitted, both schemes are permitted. | | `threshold` | `number` | `1024` | The minimum response body size in bytes required to trigger compression. | | `contentTypeFilter` | `RegExp \| ((contentType: string) => boolean)` | `COMPRESSIBLE_CONTENT_TYPE_REGEX` | A regular expression or predicate function determining whether a given `Content-Type` header qualifies for compression. | Sources: [src/middleware/compress/index.ts:16-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L16-L22), [src/middleware/compress/index.ts:51-54](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L51-L54), [src/middleware/compress/index.ts:70-74](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L70-L74) ```typescript const app = new Hono() app.use(compress()) // Compress only JSON responses app.use(compress({ contentTypeFilter: /^application\/json/ })) // Compress based on custom Content-Type logic app.use(compress({ contentTypeFilter: (type) => COMPRESSIBLE_CONTENT_TYPE_REGEX.test(type) || type === "application/x-myformat" })) ``` Sources: [src/middleware/compress/index.ts:57-68](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L57-L68) > [!NOTE] > If the `encoding` option is omitted, the candidate list defaults to `['gzip', 'deflate']`, allowing selection based on the client's `Accept-Encoding` header with `gzip` prioritized when both are weighted equally. Sources: [src/middleware/compress/index.ts:12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L12), [src/middleware/compress/index.ts:52](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L52), [src/middleware/compress/index.ts:72](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L72) ## Accept-Encoding negotiation and parsing ### Parsing mechanisms and whitespace handling Client requests specify supported compression formats using the `Accept-Encoding` header. Hono processes this string by iterating through characters, parsing comma-separated accept values, and extracting associated parameter definitions such as quality factors. During parsing, whitespace characters—specifically ASCII space (32), horizontal tab (9), line feed (10), and carriage return (13)—are inspected and skipped using dedicated utility helpers. ```typescript const isWhitespace = (char: number): boolean => char === 32 || char === 9 || char === 10 || char === 13 const consumeWhitespace = (acceptHeader: string, startIndex: number): number => { while (startIndex < acceptHeader.length) { if (!isWhitespace(acceptHeader.charCodeAt(startIndex))) { break } startIndex++ } return startIndex } ``` Sources: [src/utils/accept.ts:7-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L7-L18) > [!NOTE] > The `isWhitespace` helper evaluates character code points directly, allowing `consumeWhitespace` to advance the traversal index past any leading or intervening spaces, tabs, or newlines without allocating temporary substrings. Sources: [src/utils/accept.ts:7-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L7-L18) ### Call-chain execution walkthrough When a response is evaluated for compression, the execution flow traverses through specific parsing and selection steps: 1. `compress` inspects the response and retrieves the `Accept-Encoding` header from the request object. Sources: [src/middleware/compress/index.ts:103-104](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L103-L104) 2. `selectEncoding` receives the header string and candidate array, invoking `parseAccept` to transform the raw header into structured objects. Sources: [src/middleware/compress/index.ts:24-31](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L24-L31) 3. `parseAccept` iterates through the header string length, calling `getNextAcceptValue` at each position. Sources: [src/utils/accept.ts:211-222](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L211-L222) 4. `getNextAcceptValue` calls `consumeWhitespace` to locate type tokens and invokes `getNextParam` to parse key-value parameter pairs. Sources: [src/utils/accept.ts:168-199](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L168-L199) 5. `getNextParam` initiates parameter scanning by calling `consumeWhitespace` on the remaining substring. Sources: [src/utils/accept.ts:66-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L66-L70) 6. `consumeWhitespace` invokes `isWhitespace` for each character code encountered during index advancement. Sources: [src/utils/accept.ts:10-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L10-L16) 7. `isWhitespace` checks whether the character code matches ASCII space, tab, line feed, or carriage return. Sources: [src/utils/accept.ts:7-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L7-L8) ```mermaid sequenceDiagram participant compress as compress/index.ts participant selectEncoding as compress/index.ts (selectEncoding) participant parseAccept as utils/accept.ts (parseAccept) participant getNextAcceptValue as utils/accept.ts (getNextAcceptValue) participant getNextParam as utils/accept.ts (getNextParam) participant consumeWhitespace as utils/accept.ts (consumeWhitespace) participant isWhitespace as utils/accept.ts (isWhitespace) compress->>selectEncoding: selectEncoding(header, candidates) selectEncoding->>parseAccept: parseAccept(header) parseAccept->>getNextAcceptValue: getNextAcceptValue(acceptHeader, i) getNextAcceptValue->>getNextParam: getNextParam(acceptHeader, i) getNextParam->>consumeWhitespace: consumeWhitespace(acceptHeader, startIndex) consumeWhitespace->>isWhitespace: isWhitespace(char) ``` Sources: [src/middleware/compress/index.ts:24-31](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L24-L31), [src/utils/accept.ts:7-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L7-L18), [src/utils/accept.ts:66-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L66-L70), [src/utils/accept.ts:168-199](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L168-L199), [src/utils/accept.ts:211-222](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L211-L222) ## Quality factors and encoding selection ### Encoding candidate evaluation and priority calculation When selecting an encoding, `selectEncoding` examines the parsed accept entries against the available compression candidates (`gzip` and `deflate`). If the `Accept-Encoding` header is undefined, the function immediately returns `undefined`. Otherwise, it invokes `parseAccept` and inspects any wildcard (`*`) quality factor (`q`) value present in the request. ```typescript const selectEncoding = ( header: string | undefined, candidates: readonly Encoding[] ): Encoding | undefined => { if (header === undefined) { return undefined } const accepts = parseAccept(header) const wildcardQ = accepts.find((a) => a.type === '*')?.q let best: { encoding: Encoding; q: number } | undefined ``` Sources: [src/middleware/compress/index.ts:24-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L24-L33) For each candidate encoding, the parser checks for an explicit match against the candidate name (case-insensitively). If an explicit directive is absent, it falls back to the wildcard quality factor or `0`. If any candidate yields a quality factor of `1`, iteration halts immediately and that encoding is returned. Otherwise, the candidate with the highest positive quality factor is selected as the best encoding. ```typescript for (const enc of candidates) { const explicit = accepts.find((a) => a.type.toLowerCase() === enc) const q = explicit ? explicit.q : (wildcardQ ?? 0) if (q === 1) { return enc } else if (q > 0 && (!best || q > best.q)) { best = { encoding: enc, q } } } return best?.encoding } ``` Sources: [src/middleware/compress/index.ts:34-44](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L24-L44) > [!NOTE] > The evaluation loop short-circuits upon encountering the first candidate with a quality factor equal to `1`, prioritizing faster decision-making for fully preferred client encodings without scanning remaining candidates. Sources: [src/middleware/compress/index.ts:37-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L37-L38) ### Quality factor sanitization rules The `parseQuality` function normalizes raw string quality values extracted from accept parameters into standard numeric scores between `0` and `1`. Missing or empty parameter values default to `1`. Special string literals and out-of-range numbers are sanitized according to the fallback rules defined below. | Input Parameter (`qVal`) | Resulting Score | Handling Rule | | :--- | :--- | :--- | | `undefined` or `''` | `1` | Default weight when parameter is omitted or empty | | `'NaN'` or `NaN` | `1` | Invalid string or NaN numerical results default to `1` | | `Infinity` | `1` | Positive infinity normalizes to maximum priority `1` | | `-Infinity` | `0` | Negative infinity normalizes to minimum priority `0` | | `< 0` or `> 1` | `1` | Out-of-bounds numeric values default to `1` | | Valid number string (`0.0`–`1.0`) | Parsed Number | Converted directly via `Number(qVal)` | ```typescript const parseQuality = (qVal?: string): number => { if (qVal === undefined) { return 1 } if (qVal === '') { return 1 } if (qVal === 'NaN') { return 0 } const num = Number(qVal) if (num === Infinity) { return 1 } if (num === -Infinity) { return 0 } if (Number.isNaN(num)) { return 1 } if (num < 0 || num > 1) { return 1 } return num } ``` Sources: [src/utils/accept.ts:240-266](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L240-L266) > [!WARNING] > Passing an out-of-bounds quality factor greater than `1` or less than `0` does not reject the encoding; instead, the sanitizer falls back to a score of `1`, treating the directive as fully preferred. Sources: [src/utils/accept.ts:261-263](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L261-L263) ## Header sanitation and malformed tokens ### Call-chain execution walkthrough When client request headers contain malformed directives or unexpected token structures, the parsing engine relies on dedicated recovery routines to bypass syntax errors without throwing exceptions. The execution flow follows a specific call-chain during error handling: `compress` invokes `selectEncoding`, which calls `parseAccept`, which iterates via `getNextAcceptValue`, and finally branches into `skipInvalidAcceptValue` when an empty or broken token is encountered. 1. `compress` initiates the validation check on the incoming request header. Sources: [src/middleware/compress/index.ts:103-104](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L103-L104) 2. `selectEncoding` receives the header string and delegates parsing to `parseAccept`. Sources: [src/utils/accept.ts:211-222](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L211-L222) 3. `parseAccept` advances through the buffer by invoking `getNextAcceptValue` at each index offset. Sources: [src/utils/accept.ts:221-222](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L221-L222) 4. `getNextAcceptValue` scans character codes for delimiters such as semicolons and commas; if a type segment is empty when a separator is reached, it passes control to `skipInvalidAcceptValue`. Sources: [src/utils/accept.ts:179-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L179-L182) 5. `skipInvalidAcceptValue` tracks quotation boundaries and escape characters (`\` at code 92, quotes at code 34) until it finds a comma (code 44) or reaches the end of the header string, safely discarding the malformed segment. Sources: [src/utils/accept.ts:46-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L46-L64) ```mermaid sequenceDiagram participant compress as compress participant selectEncoding as selectEncoding participant parseAccept as parseAccept participant getNextAcceptValue as getNextAcceptValue participant skipInvalidAcceptValue as skipInvalidAcceptValue compress->>selectEncoding: selectEncoding(accepted, candidates) selectEncoding->>parseAccept: parseAccept(header) parseAccept->>getNextAcceptValue: getNextAcceptValue(acceptHeader, i) getNextAcceptValue->>skipInvalidAcceptValue: skipInvalidAcceptValue(acceptHeader, i) ``` Sources: [src/middleware/compress/index.ts:103-104](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L103-L104), [src/utils/accept.ts:46-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L46-L64), [src/utils/accept.ts:179-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L179-L182), [src/utils/accept.ts:211-222](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L211-L222) ### Recovery logic and token boundary tracking The token scanning mechanism uses character code inspections to handle quoted strings and escape sequences safely. Inside `skipInvalidAcceptValue`, the `inQuotes` boolean flag toggles whenever a double quote (`"`, code 34) is encountered outside an escape context. When `inQuotes` is active, backslash characters (`\`, code 92) trigger an index increment that consumes the following character as an escaped literal, preventing premature quote termination. ```typescript const skipInvalidAcceptValue = (acceptHeader: string, startIndex: number): number => { let i = startIndex let inQuotes = false while (i < acceptHeader.length) { const char = acceptHeader.charCodeAt(i) if (inQuotes && char === 92) { // '\' => escape i++ } else if (char === 34) { // '"' => toggle quotes inQuotes = !inQuotes } else if (!inQuotes && char === 44) { // ',' => next accept value return i + 1 } i++ } return i } ``` Sources: [src/utils/accept.ts:46-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L46-L64) When parameter parsing encounters an unexpected assignment or malformed key structure, helper functions such as `skipInvalidParam` locate the next delimiter to resume normal iteration. If an equals sign appears where a parameter value is expected, or if parameters lack proper assignment tokens, parsing skips forward to the next semicolon or comma. > [!CAUTION] > Unescaped backslashes inside quoted accept parameters can offset quote toggling logic; the parser handles escape sequences explicitly by advancing past backslash characters during quoted string traversal. Sources: [src/utils/accept.ts:50-53](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/accept.ts#L50-L53) ## Response transformation and stream piping ### Evaluating response criteria before compression Before transforming a response body, the `compress` middleware inspects response headers and request methods to ensure safety and eligibility. Compression is bypassed if the response already contains a `Content-Encoding` or `Transfer-Encoding` header, if the request method is `HEAD`, if the content length falls below the configured threshold, or if `shouldTransform` detects a `Cache-Control: no-transform` directive. Furthermore, `shouldCompress` checks the response `Content-Type` against the `contentTypeFilter` option or the default `COMPRESSIBLE_CONTENT_TYPE_REGEX` pattern. ```typescript const contentLength = ctx.res.headers.get('Content-Length') // Check if response should be compressed if ( ctx.res.headers.has('Content-Encoding') || // already encoded ctx.res.headers.has('Transfer-Encoding') || // already encoded or chunked ctx.req.method === 'HEAD' || // HEAD request (contentLength && Number(contentLength) < threshold) || // content-length below threshold !shouldCompress(ctx.res) || // not compressible type !shouldTransform(ctx.res) // cache-control: no-transform ) { return } ``` Sources: [src/middleware/compress/index.ts:89-101](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L89-L101) ### Piping through CompressionStream and header adjustments Once eligibility is confirmed and a valid encoding is negotiated, the middleware instantiates a web standard `CompressionStream` with the selected encoding type (`gzip` or `deflate`). The original response body is piped through the compression stream via `ctx.res.body.pipeThrough(stream)`, and a new `Response` object replaces `ctx.res`. The `Content-Length` header is removed because compressed stream output changes the payload size, while `Content-Encoding` is updated to match the chosen algorithm. Additionally, if a strong `ETag` header is present, it is converted into a weak `ETag` prefixed with `W/` since the compressed representation is not byte-identical to the original source. ```typescript // Compress the response const stream = new CompressionStream(encoding) ctx.res = new Response(ctx.res.body.pipeThrough(stream), ctx.res) ctx.res.headers.delete('Content-Length') ctx.res.headers.set('Content-Encoding', encoding) // Convert strong ETag to weak ETag since compressed content is not byte-identical const etag = ctx.res.headers.get('ETag') if (etag && !etag.startsWith('W/')) { ctx.res.headers.set('ETag', `W/${etag}`) } ``` Sources: [src/middleware/compress/index.ts:109-119](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L109-L119) > [!WARNING] > Strong ETags must be converted to weak ETags (`W/`) following compression because on-the-fly transformations alter byte-level payload hashes, which would otherwise invalidate conditional request validations against uncompressed caches. Sources: [src/middleware/compress/index.ts:115-119](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/compress/index.ts#L115-L119) ## Related - [ETag and Cache](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/etag-and-cache) - [Streaming and SSE](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/helpers-and-tooling/streaming-and-sse) --- ## Technical docs: Logger and Timing URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/logger-and-timing
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/logger/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts) - [src/middleware/timing/timing.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts) - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts) - [src/middleware/timing/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/index.ts) - [src/helper/dev/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/dev/index.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/utils/color.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts) - [src/middleware/etag/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts) - [src/middleware/request-id/request-id.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts) - [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/adapter/lambda-edge/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/handler.ts) - [src/middleware/etag/digest.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts) - [src/middleware/request-id/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts) - [src/middleware/pretty-json/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/pretty-json/index.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/utils/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/stream.ts) - [src/adapter/lambda-edge/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts) - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/adapter/vercel/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/conninfo.ts) - [src/adapter/netlify/mod.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/mod.ts)
## Overview The `logger` middleware intercepts incoming requests, tracks elapsed execution time, and records access logs via configurable print functions. Sources: [src/middleware/logger/index.ts:50-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L50-L94) It applies terminal styling and humanized duration formatting based on dynamic runtime environment color detection. Sources: [src/middleware/logger/index.ts:15-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L15-L46), [src/utils/color.ts:36-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts#L36-L55) Simultaneously, the `timing` middleware leverages context variable augmentation to instrument operational metrics and compile them into standard Server-Timing HTTP response headers. Sources: [src/middleware/timing/timing.ts:10-202](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L10-L202), [src/middleware/timing/index.ts:1-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/index.ts#L1-L7) ## Logger middleware architecture and dispatch ### Interception and Request Lifecycle The `logger` middleware returns an asynchronous `MiddlewareHandler` that intercepts every incoming request dispatched through the routing layer. Upon invocation, it extracts the HTTP method and URL from the request object (`c.req`), isolates the relative request path by locating the first forward slash following the protocol scheme, and immediately logs the incoming request using the `LogPrefix.Incoming` prefix (`<--`). ```typescript export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => { return async function logger(c, next) { const { method, url } = c.req const path = url.slice(url.indexOf('/', 8)) await log(fn, LogPrefix.Incoming, method, path) const start = Date.now() await next() await log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start)) } } ``` Sources: [src/middleware/logger/index.ts:81-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L81-L94) > [!NOTE] > The path slicing logic `url.slice(url.indexOf('/', 8))` assumes standard absolute URLs where the pathname starts after the protocol delimiter (e.g., `http://` or `https://`). > Sources: [src/middleware/logger/index.ts:85-85](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L85-L85) ### Access Logging and Prefixes The core logging dispatcher `log` formats output depending on whether the log entry represents an incoming request or an outgoing response. It accepts an optional custom print function `fn` which defaults to `console.log`. | Log Prefix Constant | Value | Lifecycle Phase | Formatted Output Structure | | :--- | :--- | :--- | :--- | | `LogPrefix.Incoming` | `'<--'` | Request Entry | `<-- ${method} ${path}` | | `LogPrefix.Outgoing` | `'-->'` | Response Exit | `--> ${method} ${path} ${status} ${elapsed}` | | `LogPrefix.Error` | `'xxx'` | Error State | Unused directly in `logger` middleware | ```typescript enum LogPrefix { Outgoing = '-->', Incoming = '<--', Error = 'xxx', } async function log( fn: PrintFunc, prefix: string, method: string, path: string, status: number = 0, elapsed?: string ) { const out = prefix === LogPrefix.Incoming ? `${prefix} ${method} ${path}` : `${prefix} ${method} ${path} ${await colorStatus(status)} ${elapsed}` fn(out) } ``` Sources: [src/middleware/logger/index.ts:9-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L9-L13), [src/middleware/logger/index.ts:50-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L50-L63) ## Colorized status codes and formatting ### ANSI terminal styling and status colors The `colorStatus` function evaluates HTTP response status codes and wraps them in ANSI escape sequences when terminal colors are enabled. It divides the numeric status by 100 and floors the result to determine the response category. Success codes, redirects, client errors, and server errors each map to a distinct color code. If color support is disabled, the raw status number is returned as a plain string. Sources: [src/middleware/logger/index.ts:28-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L28-L46) | Status Range / Category | ANSI Color Code | Mapped Meaning / Terminal Style | | :--- | :--- | :--- | | `5xx` | `\x1b[31m` | Red (Server Error) | | `4xx` | `\x1b[33m` | Yellow (Client Warning / Error) | | `3xx` | `\x1b[36m` | Cyan (Redirect) | | `2xx` | `\x1b[32m` | Green (Success) | | Fallback / Other | None | Plain string representation (e.g., `101`) | ```typescript const colorStatus = async (status: number) => { const colorEnabled = await getColorEnabledAsync() if (colorEnabled) { switch ((status / 100) | 0) { case 5: // red = error return `\x1b[31m${status}\x1b[0m` case 4: // yellow = warning return `\x1b[33m${status}\x1b[0m` case 3: // cyan = redirect return `\x1b[36m${status}\x1b[0m` case 2: // green = success return `\x1b[32m${status}\x1b[0m` } } return `${status}` } ``` Sources: [src/middleware/logger/index.ts:28-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L28-L46) > [!NOTE] > Fallback handling ensures unmapped or non-standard status codes like `101` (Switching Protocols) render cleanly across runtimes such as Bun and Deno even when explicit ANSI styling cases are absent. > Sources: [src/middleware/logger/index.ts:42-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L42-L45) ### Dynamic runtime color detection Runtime color detection is handled through a structured sequence starting at the `logger` middleware and resolving through `log`, `colorStatus`, `getColorEnabledAsync`, and `getColorEnabled`. The asynchronous `getColorEnabledAsync` checks if the execution environment is running on Cloudflare Workers by inspecting `navigator.userAgent`. If true, it dynamically imports `cloudflare:workers` to check whether the `NO_COLOR` environment variable is present in the worker environment bindings. Otherwise, it delegates to the synchronous `getColorEnabled` helper. Sources: [src/utils/color.ts:36-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts#L36-L55) The synchronous `getColorEnabled` function inspects `globalThis` for `Deno` and `process` globals. It checks `Deno.noColor` if present, or checks whether `NO_COLOR` exists within `process.env`. If either flag is detected, color output is disabled. Sources: [src/utils/color.ts:14-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts#L14-L27) ```typescript export function getColorEnabled(): boolean { const { process, Deno } = globalThis as any const isNoColor = typeof Deno?.noColor === 'boolean' ? (Deno.noColor as boolean) : process !== undefined ? 'NO_COLOR' in process?.env : false return !isNoColor } ``` Sources: [src/utils/color.ts:14-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts#L14-L27) ### Humanized duration formatting Elapsed request execution times are processed by the `time` and `humanize` utilities. The `time` function computes the difference between the current timestamp and the start time. If the elapsed delta is below 1,000 milliseconds, it formats the value with a trailing `ms` unit. Otherwise, it rounds the delta into seconds with a trailing `s` unit. Sources: [src/middleware/logger/index.ts:23-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L23-L26) The `humanize` helper splits and formats large digit sequences by inserting comma delimiters every three digits using regular expression matching, joining the resulting parts with periods. Sources: [src/middleware/logger/index.ts:15-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L15-L21) ```typescript const humanize = (times: string[]) => { const [delimiter, separator] = [',', '.'] const orderTimes = times.map((v) => v.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + delimiter)) return orderTimes.join(separator) } const time = (start: number) => { const delta = Date.now() - start return humanize([delta < 1000 ? delta + 'ms' : Math.round(delta / 1000) + 's']) } ``` Sources: [src/middleware/logger/index.ts:15-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L15-L26) ### Call-Chain Execution Walkthrough for Logger and Color Resolution (`Logger -> GetColorEnabled`) When the `logger` middleware executes a request, it coordinates several functions in a strict sequential call order (`logger` → `log` → `colorStatus` → `getColorEnabledAsync` → `getColorEnabled`) to determine and log colorized statuses. The execution flow follows this exact sequence: 1. **`logger`** (defined in `src/middleware/logger/index.ts:81-94`) initiates the [request lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle), invokes `await next()`, and then calls `log()` with outgoing parameters including the response status. Sources: [src/middleware/logger/index.ts:81-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L81-L94) 2. **`log`** (defined in `src/middleware/logger/index.ts:50-63`) constructs the log message string, awaiting `colorStatus(status)` to format the numeric status code. Sources: [src/middleware/logger/index.ts:50-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L50-L63) 3. **`colorStatus`** (defined in `src/middleware/logger/index.ts:28-46`) evaluates whether terminal colors are enabled by invoking `getColorEnabledAsync()`. Sources: [src/middleware/logger/index.ts:28-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L28-L46) 4. **`getColorEnabledAsync`** (defined in `src/utils/color.ts:36-55`) checks Cloudflare Workers bindings or delegates directly to `getColorEnabled()`. Sources: [src/utils/color.ts:36-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts#L36-L55) 5. **`getColorEnabled`** (defined in `src/utils/color.ts:14-27`) inspects `Deno.noColor` and `process.env.NO_COLOR` to determine color support status. Sources: [src/utils/color.ts:14-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts#L14-L27) ```mermaid sequenceDiagram participant Logger as logger (index.ts) participant LogFn as log (index.ts) participant ColorStatus as colorStatus (index.ts) participant ColorAsync as getColorEnabledAsync (color.ts) participant ColorSync as getColorEnabled (color.ts) Logger->>LogFn: log(fn, Outgoing, method, path, status, elapsed) LogFn->>ColorStatus: colorStatus(status) ColorStatus->>ColorAsync: getColorEnabledAsync() ColorAsync->>ColorSync: getColorEnabled() ColorSync-->>ColorAsync: returns boolean ColorAsync-->>ColorStatus: returns boolean ColorStatus-->>LogFn: returns styled status string LogFn->>Logger: passes formatted log string to print fn ``` Sources: [src/middleware/logger/index.ts:28-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L28-L30), [src/middleware/logger/index.ts:50-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L50-L63), [src/middleware/logger/index.ts:81-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts#L81-L94), [src/utils/color.ts:14-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts#L14-L27), [src/utils/color.ts:36-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/color.ts#L36-L55) ## Server-Timing middleware and metrics collection ### Public interface and configuration The `timing` middleware factory accepts an optional `TimingOptions` configuration object to control metric collection behavior and response header generation. It exports `TimingVariables`, which augments the Hono `ContextVariableMap` interface via module augmentation in `src/middleware/timing/index.ts`. | Option | Type | Default | Purpose | | :--- | :--- | :--- | :--- | | `total` | `boolean` | `true` | Appends a total response time metric automatically. | | `enabled` | `boolean \| ((c: Context) => boolean)` | `true` | Controls whether timing headers are appended to the response. | | `totalDescription` | `string` | `'Total Response Time'` | Description text assigned to the total response time metric. | | `autoEnd` | `boolean` | `true` | Automatically calls `endTime` on all active timers at the end of the request. | | `crossOrigin` | `boolean \| string \| ((c: Context) => boolean \| string)` | `false` | Specifies origins permitted to read the `Server-Timing` headers via `Timing-Allow-Origin`. | ```typescript interface TimingOptions { total?: boolean enabled?: boolean | ((c: Context) => boolean) totalDescription?: string autoEnd?: boolean crossOrigin?: boolean | string | ((c: Context) => boolean | string) } ``` Sources: [src/middleware/timing/timing.ts:22-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L22-L28) ```typescript import type { TimingVariables } from './timing' export { TimingVariables } export { timing, setMetric, startTime, endTime, wrapTime } from './timing' declare module '../..' { interface ContextVariableMap extends TimingVariables {} } ``` Sources: [src/middleware/timing/index.ts:1-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/index.ts#L1-L8) > [!NOTE] > If `c.get('metric')` is already populated when the timing middleware executes, it bypasses re-initialization and immediately invokes `next()`. > Sources: [src/middleware/timing/timing.ts:89-91](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L89-L91) ### Metric collection lifecycle The timestamp resolution routine `getTime` attempts to use high-resolution performance timers via `performance.now()`, falling back to `Date.now()` if an error occurs. ```typescript const getTime = (): number => { try { return performance.now() } catch {} return Date.now() } ``` Sources: [src/middleware/timing/timing.ts:30-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L30-L35) During an incoming request, the middleware initializes an empty headers array and a timers map stored in the context under the `'metric'` key. If `options.total` is enabled, it records a starting entry for `'total'`. After awaiting `next()`, it finalizes the total timer, iterates through any remaining timers if `options.autoEnd` is active, evaluates whether insertion is enabled, and populates the `Server-Timing` and `Timing-Allow-Origin` response headers. ```typescript return async function timing(c, next) { const headers: string[] = [] const timers = new Map() if (c.get('metric')) { return await next() } c.set('metric', { headers, timers }) if (options.total) { startTime(c, 'total', options.totalDescription) } await next() if (options.total) { endTime(c, 'total') } if (options.autoEnd) { timers.forEach((_, key) => { endTime(c, key) }) } const enabled = typeof options.enabled === 'function' ? options.enabled(c) : options.enabled if (enabled) { c.res.headers.append('Server-Timing', headers.join(',')) const crossOrigin = typeof options.crossOrigin === 'function' ? options.crossOrigin(c) : options.crossOrigin if (crossOrigin) { c.res.headers.append( 'Timing-Allow-Origin', typeof crossOrigin === 'string' ? crossOrigin : '*' ) } } } ``` Sources: [src/middleware/timing/timing.ts:85-125](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L85-L125) ## Operational timers and metric instrumentation ### Manual duration recording utilities Instrumenting request handlers relies on explicit helper functions to capture metrics and active timer intervals: `setMetric`, `startTime`, and `endTime`. Each utility verifies that the context contains an initialized `'metric'` store; if the middleware has been omitted from the route, a warning message is emitted to the console and execution returns without error. ```typescript export const setMetric: SetMetric = ( c: Context, name: string, valueDescription: number | string | undefined, description?: string, precision?: number ) => { const metrics = c.get('metric') if (!metrics) { console.warn('Metrics not initialized! Please add the `timing()` middleware to this route!') return } ``` Sources: [src/middleware/timing/timing.ts:149-160](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L149-L160) ```typescript export const startTime = (c: Context, name: string, description?: string) => { const metrics = c.get('metric') if (!metrics) { console.warn('Metrics not initialized! Please add the `timing()` middleware to this route!') return } metrics.timers.set(name, { description, start: getTime() }) } ``` Sources: [src/middleware/timing/timing.ts:187-194](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L187-L194) ```typescript export const endTime = (c: Context, name: string, precision?: number) => { const metrics = c.get('metric') if (!metrics) { console.warn('Metrics not initialized! Please add the `timing()` middleware to this route!') return } const timer = metrics.timers.get(name) if (!timer) { console.warn(`Timer "${name}" does not exist!`) return } ``` Sources: [src/middleware/timing/timing.ts:208-218](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L208-L218) > [!WARNING] > Calling `startTime`, `endTime`, or `setMetric` without registering the `timing()` middleware first will trigger a console warning and fail to attach any headers. > Sources: [src/middleware/timing/timing.ts:157-159](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L157-L159), [src/middleware/timing/timing.ts:189-191](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L189-L191), [src/middleware/timing/timing.ts:210-212](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L210-L212) ### Parameter signatures and metrics formatting The `setMetric` function supports overloaded call signatures to handle both numeric duration measurements and value-less metadata flags. When a numeric value is passed, it formats the duration string using a specified precision, defaulting to one decimal place. ```typescript interface SetMetric { (c: Context, name: string, value: number, description?: string, precision?: number): void (c: Context, name: string, description?: string): void } ``` Sources: [src/middleware/timing/timing.ts:128-132](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L128-L132) ```typescript if (typeof valueDescription === 'number') { const dur = valueDescription.toFixed(precision || 1) const metric = description ? `${name};dur=${dur};desc="${description}"` : `${name};dur=${dur}` metrics.headers.push(metric) } else { // Value-less metric const metric = valueDescription ? `${name};desc="${valueDescription}"` : `${name}` metrics.headers.push(metric) } } ``` Sources: [src/middleware/timing/timing.ts:161-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L161-L173) > [!TIP] > Use `setMetric` with string values to inject string annotations or environment labels such as region identifiers directly into the `Server-Timing` header output. > Sources: [src/middleware/timing/timing.ts:167-172](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L167-L172) ## Server-Timing response header serialization ### Header formatting rules and metric strings Collected metric names, durations, and optional descriptions are serialized into standard HTTP header values during the final phase of the timing middleware execution. Depending on the input arguments passed to `setMetric` or recorded by active timers via `endTime`, the serialization formats metrics as either value-bearing entries or value-less metadata flags. ```typescript if (typeof valueDescription === 'number') { const dur = valueDescription.toFixed(precision || 1) const metric = description ? `${name};dur=${dur};desc="${description}"` : `${name};dur=${dur}` metrics.headers.push(metric) } else { // Value-less metric const metric = valueDescription ? `${name};desc="${valueDescription}"` : `${name}` metrics.headers.push(metric) } } ``` Sources: [src/middleware/timing/timing.ts:161-173](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L161-L173) > [!NOTE] > Numeric metrics format their duration using `.toFixed(precision || 1)`, appending a `dur` attribute followed by a quoted `desc` attribute if a description is provided. > Sources: [src/middleware/timing/timing.ts:161-166](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L161-L166) ### Response injection and cross-origin configuration Once enabled status is verified, accumulated entries in the header array are joined with commas and appended to the response under the `Server-Timing` header key. If cross-origin reading is configured, a complementary `Timing-Allow-Origin` header is attached using either the specified string origin or a wildcard `*`. ```typescript const enabled = typeof options.enabled === 'function' ? options.enabled(c) : options.enabled if (enabled) { c.res.headers.append('Server-Timing', headers.join(',')) const crossOrigin = typeof options.crossOrigin === 'function' ? options.crossOrigin(c) : options.crossOrigin if (crossOrigin) { c.res.headers.append( 'Timing-Allow-Origin', typeof crossOrigin === 'string' ? crossOrigin : '*' ) } } ``` Sources: [src/middleware/timing/timing.ts:110-124](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L110-L124) > [!WARNING] > The `crossOrigin` option accepts booleans, strings, or dynamic evaluation functions taking the request context `c`, allowing fine-grained control over external performance monitoring access. > Sources: [src/middleware/timing/timing.ts:27-27](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L27-L27), [src/middleware/timing/timing.ts:115-116](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L115-L116) ## Related - [Request ID and Language](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/request-id-and-language) --- ## Technical docs: Request ID and Language URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/request-id-and-language
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/request-id/request-id.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts) - [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts) - [src/middleware/request-id/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/middleware/logger/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts) - [src/middleware/language/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/index.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/ip-restriction/index.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/middleware/etag/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/index.ts) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/middleware/method-override/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts) - [src/helper/accepts/accepts.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/accepts.ts) - [src/middleware/timing/timing.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/middleware/context-storage/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts) - [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts) - [src/helper/ssg/middleware.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/middleware.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/adapter/vercel/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/vercel/conninfo.ts) - [src/adapter/lambda-edge/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [src/utils/headers.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/headers.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/helper/accepts/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/index.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts) - [src/middleware/trailing-slash/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts)
## Overview Hono provides specialized middleware and utilities for tracking requests and managing client localization across web applications. The request ID middleware assigns or propagates unique correlation identifiers via configurable headers and generator functions, integrating directly with TypeScript type definitions through declaration merging. For localization, language detection strategies parse quality-weighted `Accept-Language` headers, query parameters, cookies, and URL paths, normalizing locale tags against supported options and persisting selections to optimize downstream handling. Sources: [src/middleware/request-id/request-id.ts:9-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L9-L56), [src/middleware/request-id/index.ts:5-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts#L5-L7), [src/middleware/language/language.ts:13-172](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L13-L172), [src/middleware/language/index.ts:10-12](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/index.ts#L10-L12) ## Request identifier generation and propagation ### Middleware configuration and options The `requestId` middleware factory accepts an optional `RequestIdOptions` configuration object defining constraints for request tracking. If omitted, the middleware defaults to a maximum length of 255 characters, uses `X-Request-Id` as the header name, and generates identifiers using `crypto.randomUUID()`. | Option | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `limitLength` | `number` | `255` | Maximum allowed character length for incoming or generated request IDs. | | `headerName` | `string` | `'X-Request-Id'` | HTTP header name used to read incoming request IDs and inject outgoing response IDs. | | `generator` | `(c: Context) => string` | `() => crypto.randomUUID()` | Custom function invoked to produce a new identifier when validation fails or no header is present. | Sources: [src/middleware/request-id/request-id.ts:13-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L13-L17), [src/middleware/request-id/request-id.ts:41-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L41-L45) ### Generation and validation flow When an incoming request hits the middleware, it checks whether `headerName` is configured. If `headerName` is provided, the middleware reads the corresponding header from the request object. If `headerName` is an empty string, `c.req.header()` evaluates to an undefined or unqueried state. ```mermaid flowchart TD Start([Incoming Request]) --> CheckHeader{headerName set?} CheckHeader -- Yes --> ReadHeader[Read c.req.header headerName] CheckHeader -- No --> Gen[Invoke generator function] ReadHeader --> Validate{Valid ID?} Validate -- Missing, > limitLength, or matches /[^\w\-=]/ --> Gen Validate -- Valid format and length --> Assign[Store reqId in Context] Gen --> Assign Assign --> Inject{headerName set?} Inject -- Yes --> SetHeader[Inject header into Response] Inject -- No --> Next["Call await next()"] SetHeader --> Next Next --> End([End Middleware]) ``` Sources: [src/middleware/request-id/request-id.ts:46-58](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L46-L58) > [!WARNING] > Incoming request identifiers must pass strict validation checks before being accepted. If an incoming header value exceeds `limitLength` or contains characters outside alphanumeric values, hyphens, and equals signs (`/[^\w\-=]/`), the middleware discards the header value and invokes the `generator` function instead. Sources: [src/middleware/request-id/request-id.ts:49-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L49-L51) ## Context variable typing for request identifiers ### Type definition and declaration merging The request ID middleware exposes the `RequestIdVariables` type definition, which defines the variable map shape for [context storage](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/context-storage). To provide seamless type safety when accessing request identifiers via `c.get('requestId')`, the module extends Hono's global `ContextVariableMap` interface through declaration merging. ```typescript export type RequestIdVariables = { requestId: string } ``` Sources: [src/middleware/request-id/request-id.ts:9-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L9-L11) ```typescript import type { RequestIdVariables } from './request-id' export type { RequestIdVariables } export { requestId } from './request-id' declare module '../..' { interface ContextVariableMap extends RequestIdVariables {} } ``` Sources: [src/middleware/request-id/index.ts:1-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts#L1-L7) | Exported Member | Type / Signature | Target Interface | Purpose | | :--- | :--- | :--- | :--- | | `RequestIdVariables` | `{ requestId: string }` | `ContextVariableMap` | Defines the mapping from the `'requestId'` key to its string value type within application instances. | | `requestId` | `(options?: RequestIdOptions) => MiddlewareHandler` | N/A | Middleware factory that assigns the generated ID to `requestId` via `c.set()`. | Sources: [src/middleware/request-id/request-id.ts:9-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L9-L11), [src/middleware/request-id/request-id.ts:41-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L41-L45), [src/middleware/request-id/index.ts:1-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts#L1-L7) ### Context retrieval and instantiation Developers integrate the typed variables by importing `RequestIdVariables` and passing it to the generic `Hono` application constructor. Once registered, handlers can retrieve the identifier using `c.get('requestId')` with full type inference. ```ts type Variables = RequestIdVariables const app = new Hono<{ Variables: Variables }>() app.use(requestId()) app.get('/', (c) => { console.log(c.get('requestId')) return c.text('Hello World!') }) ``` Sources: [src/middleware/request-id/request-id.ts:31-39](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts#L31-L39) > [!NOTE] > When importing from `hono/request-id`, declaration merging automatically augments the global `ContextVariableMap` so that manual generic binding is optional if utilizing global type environments, while explicit generic parameterization ensures strict scoped typing in modular applications. Sources: [src/middleware/request-id/index.ts:5-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts#L5-L7) ## Accept-Language header parsing and quality weighting ### Parsing and quality score extraction The `parseAcceptLanguage` function extracts language tags and their associated quality values (`q`) from raw `Accept-Language` headers. It delegates the underlying string decomposition to the utility function `parseAccept`, then maps each returned record to an array of objects containing the language type (`lang`) and quality weighting (`q`). ```typescript export function parseAcceptLanguage(header: string): Array<{ lang: string; q: number }> { return parseAccept(header).map(({ type, q }) => ({ lang: type, q })) } ``` Sources: [src/middleware/language/language.ts:74-76](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L74-L76) When matching headers explicitly via helpers, the `accepts` function retrieves the header specified in configuration options and processes the values. If the header is missing, it falls back to the default configured string. ```typescript export const accepts = (c: Context, options: acceptsOptions): string => { const acceptHeader = c.req.header(options.header) if (!acceptHeader) { return options.default } const accepts = parseAccept(acceptHeader) const match = options.match || defaultMatch return match(accepts, options) } ``` Sources: [src/helper/accepts/accepts.ts:40-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/accepts.ts#L40-L49) ### Quality weighting and default matching The `defaultMatch` function sorts parsed accept objects in descending order by their quality weighting score (`q`) and returns the first language tag that exists within the supported languages array. If no matches are found, it yields the configured default string. ```typescript export const defaultMatch = (accepts: Accept[], config: acceptsConfig): string => { const { supports, default: defaultSupport } = config const accept = accepts.sort((a, b) => b.q - a.q).find((accept) => supports.includes(accept.type)) return accept ? accept.type : defaultSupport } ``` Sources: [src/helper/accepts/accepts.ts:21-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/accepts.ts#L21-L25) | Configuration Property | Type | Default / Scope | Purpose | | :--- | :--- | :--- | :--- | | `header` | `AcceptHeader` | Required | Specifies the HTTP header key to inspect (e.g., `'Accept-Language'`). | | `supports` | `string[]` | Required | Array of supported language codes or media types. | | `default` | `string` | Required | Fallback value returned when no entries match supported options. | | `match` | `(accepts: Accept[], config: acceptsConfig) => string` | Optional | Custom matching strategy function replacing `defaultMatch`. | Sources: [src/helper/accepts/accepts.ts:11-19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/accepts.ts#L11-L19) > [!WARNING] > The `defaultMatch` algorithm strictly iterates through sorted quality values from highest to lowest. If a client provides multiple supported languages with identical quality scores, the order in which they appear in the raw header string dictates precedence based on the underlying parser's stability. Sources: [src/helper/accepts/accepts.ts:21-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/accepts/accepts.ts#L21-L23) ## Language detector strategy and lookup chain ### Detection strategies and mapping The language module supports four distinct detection strategies encapsulated within the `DetectorType` union: `'path'`, `'querystring'`, `'cookie'`, and `'header'`. Each strategy extracts a raw string candidate from different parts of the incoming HTTP request context, which is then processed through `normalizeLanguage` against the configured `supportedLanguages`. The `detectors` mapping object binds these strategy identifiers to their respective implementation functions. | Strategy Name | Implementation Function | Source Location | Description | | :--- | :--- | :--- | :--- | | `querystring` | `detectFromQuery` | `src/middleware/language/language.ts:128-131` | Inspects URL query parameters using `lookupQueryString`. | | `cookie` | `detectFromCookie` | `src/middleware/language/language.ts:136-139` | Retrieves cookie values using `lookupCookie`. | | `header` | `detectFromHeader` | `src/middleware/language/language.ts:144-162` | Parses `Accept-Language` headers via `lookupFromHeaderKey`. | | `path` | `detectFromPath` | `src/middleware/language/language.ts:167-172` | Extracts path segments from the URL path at `lookupFromPathIndex`. | Sources: [src/middleware/language/language.ts:10-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L10-L10), [src/middleware/language/language.ts:128-182](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L128-L182) ### Normalization and RFC 4647 lookup The `normalizeLanguage` function validates and cleanses raw language strings using progressive truncation adhering to RFC 4647 lookup rules. When `ignoreCase` is enabled, candidate strings and supported entries are lowercased for comparison. If an exact match fails, the function splits the language code by hyphens and progressively truncates segments from right to left until a matching prefix is found in `supportedLanguages`. ```typescript export const normalizeLanguage = ( lang: string | null | undefined, options: DetectorOptions ): string | undefined => { if (!lang) { return undefined } try { let normalizedLang = lang.trim() if (options.convertDetectedLanguage) { normalizedLang = options.convertDetectedLanguage(normalizedLang) } const compLang = options.ignoreCase ? normalizedLang.toLowerCase() : normalizedLang const compSupported = options.supportedLanguages.map((l) => options.ignoreCase ? l.toLowerCase() : l ) // Exact match const exactIndex = compSupported.indexOf(compLang) if (exactIndex !== -1) { return options.supportedLanguages[exactIndex] } // Progressive truncation (RFC 4647 Lookup) const parts = compLang.split('-') for (let i = parts.length - 1; i > 0; i--) { const candidate = parts.slice(0, i).join('-') const prefixIndex = compSupported.indexOf(candidate) if (prefixIndex !== -1) { return options.supportedLanguages[prefixIndex] } } return undefined } catch { return undefined } } ``` Sources: [src/middleware/language/language.ts:84-123](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L84-L123) > [!WARNING] > If a custom transformation function is provided via `convertDetectedLanguage`, it executes before normalization and case-folding, allowing pre-processing of non-standard locale tokens. Sources: [src/middleware/language/language.ts:94-96](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L94-L96) ### Validation of detector options Before runtime execution, `validateOptions` inspects the active `DetectorOptions` configuration to ensure consistency. It verifies that `fallbackLanguage` exists within the `supportedLanguages` collection, that `lookupFromPathIndex` is non-negative, and that all entries in the `order` array correspond to valid keys within the `detectors` map. ```typescript export function validateOptions(options: DetectorOptions): void { if (!options.supportedLanguages.includes(options.fallbackLanguage)) { throw new Error('Fallback language must be included in supported languages') } if (options.lookupFromPathIndex < 0) { throw new Error('Path index must be non-negative') } if (!options.order.every((detector) => Object.keys(detectors).includes(detector))) { throw new Error('Invalid detector type in order array') } } ``` Sources: [src/middleware/language/language.ts:195-207](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L195-L207) ## Locale persistence and response caching ### Cookie-based caching strategies The language detection middleware manages detected locale persistence through the `cacheLanguage` function, which serializes resolved language codes into HTTP cookies. Caching behavior is governed by the `caches` option array and the default configuration settings. ```typescript export const DEFAULT_OPTIONS: DetectorOptions = { order: ['querystring', 'cookie', 'header'], lookupQueryString: 'lang', lookupCookie: 'language', lookupFromHeaderKey: 'accept-language', lookupFromPathIndex: 0, caches: ['cookie'], ignoreCase: true, fallbackLanguage: 'en', supportedLanguages: ['en'], cookieOptions: { sameSite: 'Strict', secure: true, maxAge: 365 * 24 * 60 * 60, httpOnly: true, }, debug: false, } ``` Sources: [src/middleware/language/language.ts:51-68](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L51-L68) The `cacheLanguage` utility inspects whether `'cookie'` is present in `options.caches` before invoking `setCookie` with the configured `lookupCookie` identifier and `cookieOptions`. ```typescript function cacheLanguage(c: Context, language: string, options: DetectorOptions): void { if (!Array.isArray(options.caches) || !options.caches.includes('cookie')) { return } try { setCookie(c, options.lookupCookie, language, options.cookieOptions) } catch (error) { if (options.debug) { console.error('Failed to cache language:', error) } } } ``` Sources: [src/middleware/language/language.ts:212-224](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L212-L224) | Option Property | Default Value | Description | | :--- | :--- | :--- | | `sameSite` | `'Strict'` | Restricts cross-site cookie transmission. | | `secure` | `true` | Ensures cookies are sent only over encrypted connections. | | `maxAge` | `31536000` (`365 * 24 * 60 * 60`) | Sets cookie lifetime to one year in seconds. | | `httpOnly` | `true` | Prevents client-side script access to the cookie. | Sources: [src/middleware/language/language.ts:61-66](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L61-L66) > [!CAUTION] > If cookie serialization fails during `cacheLanguage` execution, the error is swallowed unless `options.debug` is enabled, in which case it prints to `console.error`. Sources: [src/middleware/language/language.ts:217-223](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts#L217-L223) ### Response mutation and headers manipulation Response header modification and persistence are handled across various platform adapters and utility layers. Secure headers, timing metrics, and response cookies apply mutations directly to response headers or result objects. The secure headers middleware mutates response headers via `setHeaders`, which assigns security policies directly to `ctx.res.headers`. ```typescript function setHeaders(ctx: Context, headersToSet: [string, string][]) { headersToSet.forEach(([header, value]) => { ctx.res.headers.set(header, value) }) } ``` Sources: [src/middleware/secure-headers/secure-headers.ts:330-334](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/secure-headers/secure-headers.ts#L330-L334) Similarly, the server-timing middleware appends execution metrics and cross-origin timing allowances directly to the response headers collection. ```typescript c.res.headers.append('Server-Timing', headers.join(',')) const crossOrigin = typeof options.crossOrigin === 'function' ? options.crossOrigin(c) : options.crossOrigin if (crossOrigin) { c.res.headers.append( 'Timing-Allow-Origin', typeof crossOrigin === 'string' ? crossOrigin : '*' ) ``` Sources: [src/middleware/timing/timing.ts:113-122](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts#L113-L122) ### Platform-specific result formatting When handling requests under serverless or edge environments, response cookies and headers require explicit mapping to platform result objects. AWS Lambda processors handle cookie persistence via `setCookiesToResult` implementations across v1, v2, and ALB event structures, assigning serialized cookie arrays to `multiValueHeaders['set-cookie']` or `result.cookies`. ```typescript protected setCookiesToResult(result: APIGatewayProxyResult, cookies: string[]): void { result.cookies = cookies } ``` Sources: [src/adapter/aws-lambda/handler.ts:423-425](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/handler.ts#L423-L425) Cloudflare Pages middleware constructs a Web Standard `Context` instance wrapping the execution event request and environment bindings, parsing exceptions and HTTP exceptions into finalized `Response` instances. ```typescript return async (executionCtx) => { const context = new Context(executionCtx.request, { env: { ...executionCtx.env, eventContext: executionCtx }, executionCtx, }) let response: Response | void = undefined try { response = await middleware(context, async () => { try { context.res = await executionCtx.next() } catch (error) { if (error instanceof Error) { context.error = error } else { throw error } } }) } catch (error) { if (error instanceof Error) { context.error = error } else { throw error } } if (response) { return response } if (context.error instanceof HTTPException) { return context.error.getResponse() } if (context.error) { throw context.error } return context.res } ``` Sources: [src/adapter/cloudflare-pages/handler.ts:60-101](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts#L60-L101) ## Related - [Logger and Timing](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/logger-and-timing) --- ## Technical docs: Trailing Slash and Override URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/trailing-slash-and-override
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/method-override/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts) - [src/jsx/dom/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts) - [src/middleware/trailing-slash/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts) - [src/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/types.ts) - [src/jsx/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts) - [src/jsx/dom/hooks/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/hooks/index.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/utils/url.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/url.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/router/linear-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/linear-router/router.ts) - [src/middleware/csrf/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/csrf/index.ts) - [src/validator/validator.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/validator/validator.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/router/reg-exp-router/prepared-router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/prepared-router.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/router/trie-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/router.ts) - [src/utils/body.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts) - [src/router/trie-router/node.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/trie-router/node.ts) - [src/helper/ssg/middleware.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/ssg/middleware.ts) - [src/router/reg-exp-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/reg-exp-router/router.ts) - [src/router/pattern-router/router.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/router/pattern-router/router.ts) - [src/middleware/powered-by/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/powered-by/index.ts) - [src/middleware/pretty-json/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/pretty-json/index.ts)
## Overview The trailing slash and method override middleware modules provide essential URL normalization and protocol adaptation capabilities for Hono applications[Trailing Slash and Override](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/trailing-slash-and-override). The `trimTrailingSlash` and `appendTrailingSlash` functions normalize incoming request paths by either stripping or appending trailing slashes, supporting both unconditional redirects and fallback 404 redirection with configurable skip filters[src/middleware/trailing-slash/index.ts:44-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts#L44-L157). Concurrently, the `methodOverride` middleware enables clients to emulate RESTful mutations via standard HTML forms using custom header detection, query parameters, or form body inspection with `_method` field resolution[src/middleware/method-override/index.ts:11-134](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L11-L134). Together, these utilities streamline routing consistency and bridge browser form limitations across web standard runtimes. Sources: [src/middleware/method-override/index.ts:11-134](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L11-L134), [src/middleware/trailing-slash/index.ts:44-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts#L44-L157) ## Trailing Slash Redirection and Rewriting ### Normalization Mechanics The trailing slash middleware implementations (`trimTrailingSlash` and `appendTrailingSlash`) enforce canonical URL structures by inspecting incoming request paths and issuing permanent HTTP `301` redirects. Both factories accept configuration options governing whether redirection occurs prior to handler execution or strictly as a fallback upon encountering a `404 Not Found` response status. Redirections are restricted exclusively to `GET` and `HEAD` request methods, and root paths (`/`) are explicitly excluded from path trimming. When `alwaysRedirect` is disabled, the middleware awaits downstream handler execution (`await next()`), intercepting responses that yield a `404` status before modifying `c.res` with a redirected URL instance. Sources: [src/middleware/trailing-slash/index.ts:44-74](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts#L44-L74), [src/middleware/trailing-slash/index.ts:128-157](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts#L128-L157) > [!NOTE] > Setting `alwaysRedirect: true` evaluates the normalization condition before calling downstream handlers, which is required when using wildcard (`*`) routes that would otherwise match unnormalized paths and prevent `404` fallback triggers. Sources: [src/middleware/trailing-slash/index.ts:8-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts#L8-L16), [src/middleware/trailing-slash/index.ts:76-84](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts#L76-L84) ### Options and Skip Filters The `appendTrailingSlash` middleware supports a `skip` callback function allowing specific paths to bypass redirection rules, such as requests targeting files with extensions (`/\.\w+$/`). | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `alwaysRedirect` | `boolean` | `false` | Redirects requests before handler execution instead of waiting for a `404` response status. | | `skip` | `(path: string) => boolean` | `undefined` | Determines whether to bypass the trailing slash redirection for a specific request path. | Sources: [src/middleware/trailing-slash/index.ts:76-101](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/trailing-slash/index.ts#L76-L101) ## HTTP Method Override Execution Flow ### Middleware Configuration Options The `methodOverride` middleware factory accepts a configuration object defining the targeted application instance and the mechanism used to detect override values. The configuration type enforces mutual exclusivity across inspection strategies, ensuring that exactly one detection vector—`form`, `header`, or `query`—is specified per middleware instance. When no override key is explicitly provided for form submissions, the default field name `_method` is used. Requests arriving with the `GET` method bypass inspection entirely and immediately invoke `next()`. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `app` | `Hono` | (Required) | The Hono application instance used to dispatch the mutated request. | | `form` | `string` | `'_method'` | Form field name containing the override method name when inspecting request bodies. | | `header` | `string` | `undefined` | HTTP header name containing the override method name. | | `query` | `string` | `undefined` | Query parameter key containing the override method name. | Sources: [src/middleware/method-override/index.ts:11-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L11-L33), [src/middleware/method-override/index.ts:60-64](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L60-L64) ### Inspection and Request Mutation Strategies When an override condition is met, the middleware clones the incoming request, strips the override indicator from the payload, headers, or query string, and instantiates a new Web Standard `Request` object with the overridden HTTP method. This newly constructed request is then dispatched directly into the configured Hono application instance using `app.fetch(request, c.env, getExecutionCtx(c))`. > [!WARNING] > When processing `multipart/form-data` payloads, the middleware explicitly deletes both `content-type` and `content-length` headers from the cloned headers collection before constructing the new `Request` instance so the runtime can correctly re-calculate them for the boundary-delimited body. Sources: [src/middleware/method-override/index.ts:68-134](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L68-L134), [src/middleware/method-override/index.ts:138-146](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L138-L146) For header-based overrides, the specified header name is extracted from the incoming request, deleted from a cloned headers collection, and supplied as the `method` parameter to the dispatched request. For query-based overrides, the target query parameter is removed from the URL search parameters while preserving the original request body and headers. If no override value is detected by the active inspection branch, the middleware falls back to calling `next()`. Sources: [src/middleware/method-override/index.ts:106-136](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L106-L136) ## Form Body Parsing and Resolution ### Call-Chain Execution Walkflows The form body parsing utility supports both flat form values and complex dot-notation structures. When resolving form data, the execution follows specific call chains depending on whether all values or nested structures are processed. The first execution sequence handles parsing all values into arrays or flat fields: 1. `methodOverride` invokes `parseBody` when processing `application/x-www-form-urlencoded` or `multipart/form-data` requests. 2. `parseBody` inspects the content type header and delegates to `parseFormData`. 3. `parseFormData` calls `(request as Request).formData()` and passes the resulting `FormData` object to `convertFormDataToBodyData`. 4. `convertFormDataToBodyData` iterates over entries, checking whether `options.all` or a `[]` key suffix applies, and invokes `handleParsingAllValues`. 5. `handleParsingAllValues` assigns or pushes multiple values into array structures on the target object. Sources: [src/middleware/method-override/index.ts:92-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L92-L94), [src/utils/body.ts:94-108](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L94-L108), [src/utils/body.ts:121-132](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L121-L132), [src/utils/body.ts:142-170](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L142-L170), [src/utils/body.ts:179-197](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L179-L197) The second execution sequence handles nested keys when `options.dot` is enabled: 1. `methodOverride` invokes `parseBody` for form submissions. 2. `parseBody` forwards the request to `parseFormData`. 3. `parseFormData` retrieves form data and calls `convertFormDataToBodyData`. 4. `convertFormDataToBodyData` identifies keys containing dot characters when `options.dot` is active and triggers `handleParsingNestedValues`. 5. `handleParsingNestedValues` splits the key string by dots, guards against prototype pollution, and instantiates nested objects for intermediate keys. Sources: [src/middleware/method-override/index.ts:92-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L92-L94), [src/utils/body.ts:94-108](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L94-L108), [src/utils/body.ts:121-132](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L121-L132), [src/utils/body.ts:142-170](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L142-L170), [src/utils/body.ts:206-233](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L206-L233) ```mermaid sequenceDiagram participant MethodOverride as methodOverride participant ParseBody as parseBody participant ParseFormData as parseFormData participant ConvertFormData as convertFormDataToBodyData participant HandleValues as handleParsingAllValues / handleParsingNestedValues MethodOverride->>ParseBody: parseBody(clonedRequest) ParseBody->>ParseFormData: parseFormData(request, options) ParseFormData->>ConvertFormData: convertFormDataToBodyData(formData, options) ConvertFormData->>HandleValues: handleParsingAllValues or handleParsingNestedValues ``` Sources: [src/middleware/method-override/index.ts:92-94](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/method-override/index.ts#L92-L94), [src/utils/body.ts:94-108](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L94-L108), [src/utils/body.ts:121-132](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L121-L132), [src/utils/body.ts:142-170](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L142-L170), [src/utils/body.ts:179-197](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L179-L197), [src/utils/body.ts:206-233](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L206-L233) ### Body Parsing Options and Security Protections The body parsing utility accepts configuration options that dictate how multi-value fields and dot-notation keys are structured in the returned data object. | Option | Type | Default | Description | | :--- | :--- | :--- | :--- | | `all` | `boolean` | `false` | Parses all fields with multiple values or trailing `[]` brackets as arrays. | | `dot` | `boolean` | `false` | Parses dot-notation keys into nested JavaScript objects. | Sources: [src/utils/body.ts:42-74](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L42-L74) > [!CAUTION] > The `handleParsingNestedValues` function explicitly tests keys against the regular expression `/(?:^|\.)__proto__\./` and immediately returns without assigning values if a prototype pollution attempt is detected. Sources: [src/utils/body.ts:206-213](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/body.ts#L206-L213) ## JSX Form Action Integration ### Form Component and Server Actions Hono's JSX implementation supports progressive enhancement for forms through function-valued actions. The `form` functional component intercepts submission events when client-side DOM rendering is active, inspecting whether the event is trusted and evaluating the action handler. If the action is a function, `form` prevents default browser submission, extracts form entries into a `FormData` instance, updates the internal pending and dirty state via `useState`, and invokes the action function. If the action returns a `Promise`, it registers the asynchronous operation using `registerAction` and awaits its resolution. ```typescript export const form: FC< PropsWithChildren<{ action?: Function | string method?: 'get' | 'post' ref?: RefObject | ((e: HTMLFormElement | null) => void | (() => void)) }> > = (props) => { const { action, ...restProps } = props if (typeof action !== 'function') { // eslint-disable-next-line @typescript-eslint/no-explicit-any ;(restProps as any).action = action } const [state, setState] = useState<[FormData | null, boolean]>([null, false]) // [FormData, isDirty] const onSubmit = useCallback<(ev: SubmitEvent | CustomEvent) => void>( async (ev: SubmitEvent | CustomEvent) => { const currentAction = ev.isTrusted ? action : (ev as CustomEvent).detail[customEventFormAction] if (typeof currentAction !== 'function') { return } ev.preventDefault() const formData = new FormData(ev.target as HTMLFormElement) setState([formData, true]) const actionRes = currentAction(formData) if (actionRes instanceof Promise) { registerAction(actionRes) await actionRes } setState([null, true]) }, [] ) const ref = composeRef(props.ref, (el: HTMLFormElement) => { el.addEventListener('submit', onSubmit) return () => { el.removeEventListener('submit', onSubmit) } }) const [data, isDirty] = state state[1] = false return { tag: FormContext as unknown as Function, props: { value: { pending: data !== null, data, method: data ? 'post' : null, action: data ? action : null, }, children: { tag: 'form', props: { ...restProps, ref, }, type: 'form', ref, }, }, f: isDirty, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any } ``` Sources: [src/jsx/dom/intrinsic-element/components.ts:319-386](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts#L319-L386) > [!NOTE] > When server-side rendering is used instead of the client DOM renderer, the `form` component checks for a `PERMALINK` symbol on function actions to resolve string endpoints for non-JS environments. Sources: [src/jsx/intrinsic-element/components.ts:182-192](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L182-L192) ### Form Actionable Elements Interactive elements inside forms such as inputs and buttons can specify individual action handlers via `formAction`. The helper function `formActionableElement` intercepts clicks on elements carrying a function-valued `formAction`. When clicked, it prevents the default click behavior, locates the parent form element, and dispatches a custom `submit` event carrying the action function inside `detail` keyed by a private symbol. ```typescript const formActionableElement = ( tag: string, { formAction, ...props }: { formAction?: Function | string ref?: RefObject | ((e: HTMLInputElement) => void | (() => void)) } ) => { if (typeof formAction === 'function') { const onClick = useCallback<(ev: MouseEvent) => void>((ev: MouseEvent) => { ev.preventDefault() ;(ev.currentTarget! as HTMLInputElement).form!.dispatchEvent( new CustomEvent('submit', { detail: { [customEventFormAction]: formAction } }) ) }, []) props.ref = composeRef(props.ref, (el: HTMLInputElement) => { el.addEventListener('click', onClick) return () => { el.removeEventListener('click', onClick) } }) } return { tag, props, type: tag, ref: props.ref, // eslint-disable-next-line @typescript-eslint/no-explicit-any } as any } ``` Sources: [src/jsx/dom/intrinsic-element/components.ts:388-422](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts#L388-L422) > [!IMPORTANT] > The custom event mechanism relies on `customEventFormAction` symbol keys to securely pass function references across DOM boundaries without leaking private handlers into standard attribute serialization. Sources: [src/jsx/dom/intrinsic-element/components.ts:318-337](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts#L318-L337), [src/jsx/dom/intrinsic-element/components.ts:388-403](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts#L388-L403) ## Edge Runtime and Middleware Packaging ### Module Export Layout and Subpath Imports Hono exposes its built-in utility middleware and runtime features through fine-grained subpath exports defined in `package.json`. Each subpath provides separate type definitions (`types`), ESM imports (`import`), and CommonJS requires (`require`) to support bundlers, Node.js, and edge runtimes seamlessly. | Subpath Export | Types Entry | ESM Import Entry | CommonJS Entry | | :--- | :--- | :--- | :--- | | `./powered-by` | `./dist/types/middleware/powered-by/index.d.ts` | `./dist/middleware/powered-by/index.js` | `./dist/cjs/middleware/powered-by/index.js` | | `./pretty-json` | `./dist/types/middleware/pretty-json/index.d.ts` | `./dist/middleware/pretty-json/index.js` | `./dist/cjs/middleware/pretty-json/index.js` | | `./trailing-slash` | `./dist/types/middleware/trailing-slash/index.d.ts` | `./dist/middleware/trailing-slash/index.js` | `./dist/cjs/middleware/trailing-slash/index.js` | | `./method-override` | `./dist/types/middleware/method-override/index.d.ts` | `./dist/middleware/method-override/index.js` | `./dist/cjs/middleware/method-override/index.js` | Sources: [package.json:138-142](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L138-L142), [package.json:233-247](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json#L233-L247) ### Lightweight Utility Middleware Packaging Utility middleware such as `poweredBy` and `prettyJSON` are implemented as zero-dependency factories returning standard `MiddlewareHandler` closures. The `poweredBy` middleware accepts an optional `serverName` configuration string defaulting to `'Hono'` and appends the `X-Powered-By` response header after downstream handlers execute. ```typescript export const poweredBy = (options?: PoweredByOptions): MiddlewareHandler => { return async function poweredBy(c, next) { await next() c.res.headers.set('X-Powered-By', options?.serverName ?? 'Hono') } } ``` Sources: [src/middleware/powered-by/index.ts:30-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/powered-by/index.ts#L30-L35) > [!NOTE] > The `prettyJSON` middleware inspects response content types and query parameters according to its `PrettyOptions`, allowing formatting overrides via a configurable query parameter or the `force` flag. Sources: [src/middleware/pretty-json/index.ts:8-26](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/pretty-json/index.ts#L8-L26), [src/middleware/pretty-json/index.ts:46-55](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/pretty-json/index.ts#L46-L55) ## Related - [Request Lifecycle](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/request-lifecycle) --- ## Technical docs: Context Storage URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/traffic-middleware/context-storage
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/context-storage/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/jsx/hooks/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/hooks/index.ts) - [src/middleware/request-id/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/index.ts) - [src/jsx/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts) - [src/helper/route/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/route/index.ts) - [src/jsx/streaming.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts) - [src/middleware/language/language.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/language.ts) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/jsx/dom/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts) - [src/middleware/cache/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/cache/index.ts) - [src/middleware/timing/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/index.ts) - [src/jsx/dom/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts) - [src/middleware/timing/timing.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/timing/timing.ts) - [src/middleware/logger/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/logger/index.ts) - [src/helper/cookie/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/cookie/index.ts) - [src/middleware/request-id/request-id.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/request-id/request-id.ts) - [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts) - [src/adapter/cloudflare-pages/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-pages/handler.ts) - [src/middleware/language/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/language/index.ts) - [src/adapter/bun/server.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/bun/server.ts) - [src/adapter/lambda-edge/conninfo.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/lambda-edge/conninfo.ts) - [runtime-tests/workerd/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/workerd/index.ts) - [src/hono-base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/hono-base.ts) - [src/helper/adapter/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/adapter/index.ts) - [src/request.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/request.ts) - [src/adapter/aws-lambda/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/aws-lambda/types.ts) - [src/middleware/jwt/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jwt/index.ts) - [src/adapter/netlify/handler.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/netlify/handler.ts) - [src/utils/concurrent.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/concurrent.ts)
## Overview The Hono context storage mechanism leverages Node.js [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) `AsyncLocalStorage` to maintain request-scoped access to the [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) instance across asynchronous call boundaries without explicitly passing parameters through every function. By integrating with middleware execution flow, it binds incoming requests to an asynchronous store so that nested handlers, utility functions, and background services can retrieve active request details on demand. This architecture eliminates the need for manual context threading in deeply nested business logic while ensuring proper isolation between concurrent requests in supported runtimes. Sources: [src/middleware/context-storage/index.ts:6-11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L6-L11), [src/middleware/context-storage/index.ts:43-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L43-L47) ## AsyncLocalStorage Architecture ### Storage Mechanism The underlying storage relies on Node.js `AsyncLocalStorage` initialized as a module-level constant instance typed against the Hono [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context). This storage container maintains request isolation by capturing asynchronous execution contexts across disparate call frames. ```typescript import { AsyncLocalStorage } from 'node:async_hooks' import type { Context } from '../../context' import type { Env, MiddlewareHandler } from '../../types' const asyncLocalStorage = new AsyncLocalStorage() ``` Sources: [src/middleware/context-storage/index.ts:6-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L6-L10) > [!NOTE] > `asyncLocalStorage` is a single module-scoped singleton instance shared across all requests handled by the middleware, relying on Node's async execution tracking to segregate concurrent stores. Sources: [src/middleware/context-storage/index.ts:6-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L6-L10) ### Lifecycle Integration The middleware wraps downstream execution by passing the current `Context` instance into the `asyncLocalStorage.run` method alongside the `next` dispatch function. This anchors the active [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) to the asynchronous boundary for the duration of all subsequent middleware and route handlers. ```typescript export const contextStorage = (): MiddlewareHandler => { return async function contextStorage(c, next) { await asyncLocalStorage.run(c, next) } } ``` Sources: [src/middleware/context-storage/index.ts:43-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L43-L47) > [!WARNING] > Any asynchronous operations executed outside the scope established by `asyncLocalStorage.run` will lose access to the bound `Context`, resulting in undefined stores when calling retrieval functions. Sources: [src/middleware/context-storage/index.ts:43-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L43-L47) ## Context Storage Middleware ### Middleware Initialization The `contextStorage` factory function returns a `MiddlewareHandler` closure designed to intercept incoming request dispatches. When invoked, it yields an asynchronous middleware function that establishes the request boundary before invoking downstream handlers. ```typescript export const contextStorage = (): MiddlewareHandler => { return async function contextStorage(c, next) { await asyncLocalStorage.run(c, next) } } ``` Sources: [src/middleware/context-storage/index.ts:43-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L43-L47) ### Context Binding During Dispatch During the request dispatch cycle, the middleware binds the active `Context` instance (`c`) to the module-scoped `AsyncLocalStorage` instance by executing `asyncLocalStorage.run(c, next)`. This wraps the remaining middleware chain and route handlers (`next`) within a tracked asynchronous execution frame. ```typescript return async function contextStorage(c, next) { await asyncLocalStorage.run(c, next) } ``` Sources: [src/middleware/context-storage/index.ts:44-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L44-L46) > [!NOTE] > The `next` function passed into `asyncLocalStorage.run` ensures that all subsequent asynchronous yields, promises, and downstream handlers inherit the bound `Context` transparently. Sources: [src/middleware/context-storage/index.ts:44-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L44-L46) ## Accessing Context Outside Handlers ### Retrieval Functions The public API exports two functions for accessing the active request [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) outside of standard route handlers: `tryGetContext` and `getContext`. Both functions accept an optional generic type parameter `E` extending `Env` to type-check environment bindings and variables. `tryGetContext` queries the underlying `AsyncLocalStorage` store directly, returning the active `Context` instance or `undefined` if invoked outside an active request scope. ```typescript export const tryGetContext = (): Context | undefined => { return asyncLocalStorage.getStore() as Context | undefined } ``` Sources: [src/middleware/context-storage/index.ts:49-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L51) > [!TIP] > Use `tryGetContext` in utility functions or shared modules that may execute both within and outside of HTTP request lifecycles, allowing graceful handling of missing context states without throwing exceptions. Sources: [src/middleware/context-storage/index.ts:49-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L49-L51) ### Error Handling and Enforcement The `getContext` function wraps `tryGetContext` with a validation check, throwing an explicit error when no request context is present in the asynchronous store. This provides strict guarantees for service functions or helpers that depend unconditionally on active request bindings. ```typescript export const getContext = (): Context => { const context = tryGetContext() if (!context) { throw new Error('Context is not available') } return context } ``` Sources: [src/middleware/context-storage/index.ts:53-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L53-L59) > [!WARNING] > Calling `getContext` outside of a request scope initialized by the middleware throws a `Context is not available` error, halting execution. Sources: [src/middleware/context-storage/index.ts:55-57](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L55-L57) ## Runtime Compatibility and Constraints ### Node.js and Async Context Foundation The underlying storage mechanism relies on `AsyncLocalStorage` imported directly from the Node.js built-in `node:async_hooks` module. This restricts native context propagation support to runtimes that fully implement Node.js asynchronous hook APIs or provide compatible runtime shims. ```typescript import { AsyncLocalStorage } from 'node:async_hooks' import type { Context } from '../../context' import type { Env, MiddlewareHandler } from '../../types' const asyncLocalStorage = new AsyncLocalStorage() ``` Sources: [src/middleware/context-storage/index.ts:6-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L6-L10) > [!NOTE] > Modern JavaScript runtimes such as Node.js, Bun, and Deno natively support `AsyncLocalStorage`, ensuring seamless execution of the context storage middleware across these environments. Sources: [src/middleware/context-storage/index.ts:6-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L6-L10) ### Isolation Guarantees and Error Boundaries Because `asyncLocalStorage` is instantiated as a module-scoped constant, concurrent requests handled by the server maintain strict state isolation. Each asynchronous execution frame created by `asyncLocalStorage.run` encapsulates its own `Context` reference, preventing cross-request data leakage even during concurrent asynchronous yields. ```typescript const asyncLocalStorage = new AsyncLocalStorage() ``` Sources: [src/middleware/context-storage/index.ts:10-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L10-L10) > [!CAUTION] > Spawning independent asynchronous tasks or background promises using native `setTimeout` or unawaited promise chains outside of the tracked middleware boundary will detach execution from the active store, causing `tryGetContext` to return `undefined` and `getContext` to throw an unhandled error. Sources: [src/middleware/context-storage/index.ts:43-58](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/context-storage/index.ts#L43-L58) ## Related - [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context) --- ## Technical docs: JSX Runtime URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-runtime
Relevant source files The following files were used as context for generating this wiki page: - [src/jsx/jsx-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts) - [src/jsx/base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts) - [src/jsx/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts) - [src/jsx/dom/render.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/render.ts) - [src/jsx/streaming.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts) - [src/jsx/dom/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts) - [src/jsx/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts) - [src/jsx/jsx-dev-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-dev-runtime.ts) - [src/jsx/hooks/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/hooks/index.ts) - [src/jsx/dom/jsx-dev-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-dev-runtime.ts) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/jsx/dom/server.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts) - [src/jsx/dom/jsx-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-runtime.ts) - [src/jsx/dom/client.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/client.ts) - [src/jsx/dom/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/index.ts) - [src/helper/html/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/html/index.ts) - [src/jsx/dom/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts) - [src/utils/html.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/html.ts) - [src/jsx/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/index.ts) - [src/jsx/dom/css.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/css.ts) - [src/jsx/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts) - [src/helper/css/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/css/index.ts) - [runtime-tests/deno-jsx/deno.react-jsx.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno-jsx/deno.react-jsx.json) - [runtime-tests/deno-jsx/deno.precompile.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno-jsx/deno.precompile.json) - [src/jsx/children.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts) - [src/jsx/dom/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts) - [runtime-tests/deno/deno.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno/deno.json) - [src/jsx/intrinsic-elements.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-elements.ts) - [src/jsx/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/types.ts) - [src/jsx/constants.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/constants.ts)
## Overview Hono's JSX runtime provides both server-side rendering and client-side DOM execution models [JSX Components and Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-components-and-context), [Client DOM and Hooks](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/client-dom-and-hooks). It processes functional components and intrinsic tags through unified entry points [src/jsx/jsx-runtime.ts:6-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L6-L8), [src/jsx/jsx-dev-runtime.ts:12-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-dev-runtime.ts#L12-L25), validates and escapes attributes [src/jsx/jsx-runtime.ts:16-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L16-L49), and serializes hierarchical nodes into string buffers or browser DOM trees [src/jsx/base.ts:249-302](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L249-L302), [src/jsx/dom/render.ts:41-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/render.ts#L41-L80). Sources: [src/jsx/jsx-runtime.ts:6-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L6-L8), [src/jsx/jsx-dev-runtime.ts:12-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-dev-runtime.ts#L12-L25), [src/jsx/base.ts:249-302](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L249-L302), [src/jsx/dom/render.ts:41-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/render.ts#L41-L80), [src/jsx/jsx-runtime.ts:16-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L16-L49) ## JSX Runtime Entry Points ### Automatic and Classic Runtimes Hono supports both automatic (`react-jsx`) and development JSX transforms through dedicated module entry points [runtime-tests/deno-jsx/deno.react-jsx.json:3-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno-jsx/deno.react-jsx.json#L3-L4), [src/jsx/jsx-runtime.ts:6-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L6-L8). The primary production runtime module `hono/jsx/jsx-runtime` exports `jsx`, `jsxs`, and `Fragment` directly from `jsx-dev-runtime`, alongside `jsxTemplate` (aliased from `html`) and utility helpers such as `jsxAttr` and `jsxEscape` [[src/jsx/jsx-runtime.ts:6-14], [src/jsx/jsx-runtime.ts:51]]. ```typescript export { jsxDEV as jsx, Fragment } from './jsx-dev-runtime' export { jsxDEV as jsxs } from './jsx-dev-runtime' export type { JSX } from './jsx-dev-runtime' import { html, raw } from '../helper/html' ``` Sources: [src/jsx/jsx-runtime.ts:6-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L6-L9) The development runtime function `jsxDEV` accepts a tag, a props dictionary, and an optional key, normalizing single child properties and arrays into structured node hierarchies via `jsxFn` [src/jsx/jsx-dev-runtime.ts:12-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-dev-runtime.ts#L12-L25). ```typescript export function jsxDEV( tag: string | Function, props: Record, key?: string ): JSXNode { let node: JSXNode if (!props || !('children' in props)) { node = jsxFn(tag, props, []) } else { const children = props.children as string | HtmlEscapedString node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children]) } node.key = key return node } ``` Sources: [src/jsx/jsx-dev-runtime.ts:12-25](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-dev-runtime.ts#L12-L25) > [!NOTE] > When configured with Deno and TypeScript compiler options like `"jsx": "react-jsx"` and `"jsxImportSource": "hono/jsx"`, compiler targets resolve module specifiers against `hono/jsx/jsx-runtime` [[runtime-tests/deno-jsx/deno.react-jsx.json:3-4], [runtime-tests/deno-jsx/deno.react-jsx.json:10]]. Sources: [runtime-tests/deno-jsx/deno.react-jsx.json:3-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno-jsx/deno.react-jsx.json#L3-L4), [runtime-tests/deno-jsx/deno.react-jsx.json:10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/deno-jsx/deno.react-jsx.json#L10) ### Attribute Processing and Exports The `jsxAttr` function evaluates attribute keys and dynamic values, checking attribute name validity and formatting styles, numbers, promises, or raw escaped strings into valid markup attributes [src/jsx/jsx-runtime.ts:16-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L16-L49). | Parameter / Export | Type / Behavior | Source Reference | | :--- | :--- | :--- | | `jsx` / `jsxs` | Aliased to `jsxDEV` for automatic JSX compilation | [src/jsx/jsx-runtime.ts:6-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L6-L7) | | `Fragment` | Component grouping container exported from dev runtime | [src/jsx/jsx-runtime.ts:6](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L6) | | `jsxTemplate` | Aliased to `html` helper for template literals | [src/jsx/jsx-runtime.ts:14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L14) | | `jsxAttr` | Function validating attribute keys and formatting values | [src/jsx/jsx-runtime.ts:16-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L16-L49) | | `jsxEscape` | Identity helper function returning raw string values | [src/jsx/jsx-runtime.ts:51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L51) | Sources: [src/jsx/jsx-runtime.ts:6-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L6-L14), [src/jsx/jsx-runtime.ts:16-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L16-L49), [src/jsx/jsx-runtime.ts:51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L51) ## JSX Node Hierarchy ### Node Factories and Creation The `jsx` factory function accepts a tag, a props dictionary, and variadic children, handling prop initialization and key extraction before delegating to `jsxFn` [src/jsx/base.ts:305-317](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L305-L317). The `jsxFn` function evaluates the tag type to instantiate the appropriate hierarchy node [src/jsx/base.ts:320-352](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L320-L352). ```typescript export const jsx = (tag: string | Function, props: Props | null, ...children: Child[]): JSXNode => { props ??= {} if (children.length) { props.children = children.length === 1 ? children[0] : children } const key = props.key delete props['key'] const node = jsxFn(tag, props, children) node.key = key return node } ``` Sources: [src/jsx/base.ts:305-317](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L305-L317) When `tag` is a function, `jsxFn` returns a `JSXFunctionNode` [src/jsx/base.ts:330-331](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L330-L331). Intrinsic element tags from lookup dictionaries instantiate `JSXFunctionNode` mapped to their intrinsic renderer [src/jsx/base.ts:332-337](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L332-L337). Namespace-sensitive tags such as `svg` and `head` wrap children in a namespace context component node inside a base `JSXNode` [src/jsx/base.ts:338-349](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L338-L349), while remaining tags construct a standard `JSXNode` [src/jsx/base.ts:350-352](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L350-L352). > [!NOTE] > On the initial call to `jsxFn`, `domRenderers` bindings are assigned to intrinsic element tags using the `DOM_RENDERER` symbol property, initializing the client DOM rendering pipeline [src/jsx/base.ts:319-328](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L319-L328). Sources: [src/jsx/base.ts:319-328](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L319-L328) ### Node Types and Specialization Specialized node classes extend the hierarchy to handle functional evaluation and document fragments [src/jsx/base.ts:255-303](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L255-L303). The `JSXFunctionNode` executes functional components by invoking the component function with its properties and children, processing return values like promises, nested nodes, or escaped strings [src/jsx/base.ts:255-296](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L255-L296). The `JSXFragmentNode` implements container nodes that serialize their children directly to buffers without rendering surrounding tags [src/jsx/base.ts:299-303](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L299-L303). ```typescript class JSXFunctionNode extends JSXNode { override toStringToBuffer(buffer: StringBufferWithCallbacks): void { const { children } = this const props = { ...this.props } if (children.length) { props.children = children.length === 1 ? children[0] : children } const res = (this.tag as Function).call(null, props) // ... } } ``` Sources: [src/jsx/base.ts:255-265](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L255-L265) React-compatible element definitions and validation helpers support element checking and tree cloning [[src/jsx/types.ts:19-23], [src/jsx/base.ts:422-443]]. The `isValidElement` function validates unknown inputs [src/jsx/base.ts:422-424](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L422-L424), and `cloneElement` merges new properties and children into existing element nodes [src/jsx/base.ts:426-443](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L426-L443). Memoized functional components (`memo`) wrap components with `shallowEqual` checks to skip redundant computations [src/jsx/base.ts:354-405](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L354-L405). | Utility / Class | Target Structure / Purpose | Source Reference | | :--- | :--- | :--- | | `JSXNode` | Base structure for intrinsic and generic element nodes | [src/jsx/base.ts:338-352](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L338-L352) | | `JSXFunctionNode` | Executes functional components and intrinsic tag renderers | [src/jsx/base.ts:255-296](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L255-L296) | | `JSXFragmentNode` | Renders fragment children without enclosing HTML tags | [src/jsx/base.ts:299-303](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L299-L303) | | `isValidElement` | Type guard checking for `tag` and `props` properties | [src/jsx/base.ts:422-424](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L422-L424) | | `cloneElement` | Clones elements with merged property overrides | [src/jsx/base.ts:426-443](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L426-L443) | | `memo` | Wraps functional components with memoization and `DOM_MEMO` | [src/jsx/base.ts:384-405](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L384-L405) | Sources: [src/jsx/base.ts:255-303](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L255-L303), [src/jsx/base.ts:354-443](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L354-L443), [src/jsx/types.ts:19-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/types.ts#L19-L23) ## Attribute Normalization and Escaping ### Attribute Validation and Processing The runtime formats and serializes element attributes using the `jsxAttr` utility [src/jsx/jsx-runtime.ts:16-49](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L16-L49). Before processing any value, `jsxAttr` validates the attribute name with `isValidAttributeName`; if validation fails, it returns an empty raw string [src/jsx/jsx-runtime.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L20-L22). When the attribute name is valid, it initializes a string buffer formatted as `key="` [src/jsx/jsx-runtime.ts:23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L23). ```typescript export const jsxAttr = ( key: string, v: string | Promise | Record ): HtmlEscapedString | Promise => { if (!isValidAttributeName(key)) { return raw('') } const buffer: StringBuffer = [`${key}="`] as StringBuffer // ... ``` Sources: [src/jsx/jsx-runtime.ts:16-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L16-L23) ### Style Stringification and Value Types Attribute values are handled differently based on their runtime types [src/jsx/jsx-runtime.ts:24-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L24-L46). If the attribute key is `style` and the value is an object, `styleObjectForEach` iterates over the style properties, skipping `null` or `undefined` entries, separating properties with semicolons, and escaping the resulting string into the buffer [src/jsx/jsx-runtime.ts:24-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L24-L33). ```typescript if (key === 'style' && typeof v === 'object') { // object to style strings let styleStr = '' styleObjectForEach(v as Record, (property, value) => { if (value != null) { styleStr += `${styleStr ? ';' : ''}${property}:${value}` } }) escapeToBuffer(styleStr, buffer) buffer[0] += '"' ``` Sources: [src/jsx/jsx-runtime.ts:24-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L24-L33) > [!NOTE] > Null and undefined attribute values are suppressed entirely, returning an empty raw string instead of rendering empty attributes [src/jsx/jsx-runtime.ts:37-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L37-L38). String values undergo HTML escaping via `escapeToBuffer` before closing quotation marks are appended [src/jsx/jsx-runtime.ts:34-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L34-L36). Numbers and already-escaped HTML strings append directly without re-escaping [src/jsx/jsx-runtime.ts:39-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L39-L40). Promise instances unshift the promise into the buffer for asynchronous resolution [src/jsx/jsx-runtime.ts:41-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L41-L42), while other types are converted to strings and escaped [src/jsx/jsx-runtime.ts:43-45](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L43-L45). | Value Type | Processing Behavior | Source Reference | | :--- | :--- | :--- | | Invalid Name | Returns `raw('')` immediately | [src/jsx/jsx-runtime.ts:20-22](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L20-L22) | | Style Object | Iterates properties, formats `property:value;` pairs, escapes buffer | [src/jsx/jsx-runtime.ts:24-33](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L24-L33) | | `string` | Escapes string content via `escapeToBuffer` | [src/jsx/jsx-runtime.ts:34-36](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L34-L36) | | `null` / `undefined` | Suppresses attribute, returns `raw('')` | [src/jsx/jsx-runtime.ts:37-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L37-L38) | | `number` / `isEscaped` | Appends directly to buffer without escaping | [src/jsx/jsx-runtime.ts:39-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L39-L40) | | `Promise` | Unshifts promise into buffer for async evaluation | [src/jsx/jsx-runtime.ts:41-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L41-L42) | Sources: [src/jsx/jsx-runtime.ts:20-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts#L20-L46) ## Buffer Stringification Pipeline ### Node Serialization and Promise Interception Tree serialization converts hierarchical node structures into contiguous string chunks using a mutable `StringBufferWithCallbacks` buffer. The process evaluates functional components through `JSXFunctionNode.toStringToBuffer`, invoking component functions with props and child elements [src/jsx/base.ts:255-264](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L255-L264). When a component return value is a `Promise`, the pipeline intercepts it to support asynchronous rendering [src/jsx/base.ts:269](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L269). If global contexts are active, the implementation captures current context bindings via `globalContexts.map` to preserve them across asynchronous yields [src/jsx/base.ts:273-274](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L273-L274). It then unshifts the promise into the buffer alongside an asynchronous callback that attaches captured local contexts to resolved node instances [src/jsx/base.ts:275-283](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L275-L283). ```typescript } else if (res instanceof Promise) { if (globalContexts.length === 0) { buffer.unshift('', res) } else { // save current contexts for resuming const currentContexts: LocalContexts = globalContexts.map((c) => [c, c.values.at(-1)]) buffer.unshift( '', res.then((childRes) => { if (childRes instanceof JSXNode) { childRes.localContexts = currentContexts } return childRes }) ) } ``` Sources: [src/jsx/base.ts:269-284](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L269-L284) > [!WARNING] > Async components executing without active global contexts omit the context-capturing map step, directly unshifting the promise to minimize overhead [src/jsx/base.ts:270-272](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L270-L272). ### Primitive Handling and Fragment Flattening Non-promise component outputs undergo strict type checks before buffer insertion [src/jsx/base.ts:266-295](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L266-L295). Booleans, null, and undefined values yield immediate termination without appending anything to the buffer [src/jsx/base.ts:266-268](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L266-L268). Fragment nodes delegate traversal directly to `childrenToStringToBuffer` [src/jsx/base.ts:299-302](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L299-L302), flattening child collections without introducing wrapper elements. ```typescript export class JSXFragmentNode extends JSXNode { override toStringToBuffer(buffer: StringBufferWithCallbacks): void { childrenToStringToBuffer(this.children, buffer) } } ``` Sources: [src/jsx/base.ts:299-303](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L299-L303)] Numbers and pre-escaped objects (`isEscaped`) append directly to the current buffer chunk, and any associated rendering callbacks are pushed onto the buffer's callback array [src/jsx/base.ts:287-292](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L287-L292). All other non-escaped primitives pass through `escapeToBuffer` to guarantee safety [src/jsx/base.ts:294](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L294). | Return Type | Serialization Action | Source Reference | | :--- | :--- | :--- | | `boolean` / `null` / `undefined` | Discards output and returns immediately | [src/jsx/base.ts:266-268](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L266-L268) | | `Promise` | Unshifts promise and context capture onto the buffer | [src/jsx/base.ts:269-284](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L269-L284) | | `JSXNode` | Recursively invokes `toStringToBuffer` on the node | [src/jsx/base.ts:285-286](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L285-L286) | | `number` / `isEscaped` | Appends directly and preserves evaluation callbacks | [src/jsx/base.ts:287-292](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L287-L292) | | Other Types | Encodes value via `escapeToBuffer` | [src/jsx/base.ts:294](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L294) | Sources: [src/jsx/base.ts:266-296](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L266-L296), [src/jsx/base.ts:299-303](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts#L299-L303) ## Child Collection Traversal ### Array Normalization and Children Object Utilities The `toArray` utility normalizes child node inputs into an array representation, wrapping non-array elements in a single-element array while passing arrays through unchanged [src/jsx/children.ts:3-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L3-L4). The `Children` namespace aggregates utility methods designed for functional inspection and transformation of child node trees [src/jsx/children.ts:5-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L5-L20). ```typescript export const toArray = (children: Child): Child[] => Array.isArray(children) ? children : [children] export const Children = { map: (children: Child[], fn: (child: Child, index: number) => Child): Child[] => toArray(children).map(fn), forEach: (children: Child[], fn: (child: Child, index: number) => void): void => { toArray(children).forEach(fn) }, count: (children: Child[]): number => toArray(children).length, only: (_children: Child[]): Child => { const children = toArray(_children) if (children.length !== 1) { throw new Error('Children.only() expects only one child') } return children[0] }, toArray, } ``` Sources: [src/jsx/children.ts:3-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L3-L20) | Method | Parameters | Return Type | Description | Sources Reference | | :--- | :--- | :--- | :--- | :--- | | `toArray` | `children: Child` | `Child[]` | Normalizes single child or array into an array | [src/jsx/children.ts:3-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L3-L4) | | `Children.map` | `children: Child[], fn: (child: Child, index: number) => Child` | `Child[]` | Maps over normalized child collection | [src/jsx/children.ts:6-7](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L6-L7) | | `Children.forEach` | `children: Child[], fn: (child: Child, index: number) => void` | `void` | Iterates through normalized child collection | [src/jsx/children.ts:8-10](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L8-L10) | | `Children.count` | `children: Child[]` | `number` | Returns the total count of normalized children | [src/jsx/children.ts:11](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L11) | | `Children.only` | `_children: Child[]` | `Child` | Asserts exactly one child exists and returns it | [src/jsx/children.ts:12-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L12-L18) | | `Children.toArray` | `children: Child` | `Child[]` | Alias to module-level `toArray` | [src/jsx/children.ts:19](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L19) | Sources: [src/jsx/children.ts:3-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L3-L20) > [!WARNING] > `Children.only` evaluates normalized length and throws an explicit `Error` with message `'Children.only() expects only one child'` if the count is anything other than 1 [src/jsx/children.ts:12-17](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L12-L17). Sources: [src/jsx/children.ts:12-18](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/children.ts#L12-L18) ## Client JSX Runtime Adapters ### DOM-Targeted JSX Factories and Server Emulation The `hono/jsx/dom` runtime supplies adapters tailored for interactive client-side rendering and compatibility APIs mimicking `react-dom/server` [[src/jsx/dom/jsx-dev-runtime.ts:3-4], [src/jsx/dom/server.ts:3-4]]. The `jsxDEV` function constructs virtual DOM nodes while checking tag lookups against intrinsic element components [src/jsx/dom/jsx-dev-runtime.ts:10-13](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-dev-runtime.ts#L10-L13). If a string tag matches an entry in `intrinsic-element/components`, the factory substitutes it before returning the descriptor object containing `tag`, `type`, `props`, `key`, and `ref` [src/jsx/dom/jsx-dev-runtime.ts:11-20](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-dev-runtime.ts#L11-L20). The `Fragment` factory constructs an empty tag node utilizing `jsxDEV` with an empty string [src/jsx/dom/jsx-dev-runtime.ts:23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-dev-runtime.ts#L23). The runtime exports `jsx`, `jsxs`, and `Fragment` through standard and dev entry modules [src/jsx/dom/jsx-runtime.ts:6-8](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-runtime.ts#L6-L8). ```typescript export const jsxDEV = (tag: string | Function, props: Props, key?: string): JSXNode => { if (typeof tag === 'string' && intrinsicElementTags[tag as keyof typeof intrinsicElementTags]) { tag = intrinsicElementTags[tag as keyof typeof intrinsicElementTags] } return { tag, type: tag, props, key, ref: props.ref, } as JSXNode } export const Fragment = (props: Record): JSXNode => jsxDEV('', props, undefined) ``` Sources: [src/jsx/dom/jsx-dev-runtime.ts:10-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-dev-runtime.ts#L10-L23) Server-side rendering adapters in `hono/jsx/dom/server` provide `renderToString` and `renderToReadableStream` functions [src/jsx/dom/server.ts:65](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L65). The `renderToString` implementation evaluates element stringification, logging a warning if options are provided, and throws an error if an asynchronous component is encountered [src/jsx/dom/server.ts:21-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L21-L30). The `renderToReadableStream` utility passes non-object elements through string conversion and delegates streaming output to `renderToReadableStreamHono` [src/jsx/dom/server.ts:50-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L50-L63). ```typescript const renderToString = (element: Child, options: RenderToStringOptions = {}): string => { if (Object.keys(options).length > 0) { console.warn('options are not supported yet') } const res = element?.toString() ?? '' if (typeof res !== 'string') { throw new Error('Async component is not supported in renderToString') } return res } ``` Sources: [src/jsx/dom/server.ts:21-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L21-L30) > [!WARNING] > `renderToString` throws an explicit `Error` with the message `'Async component is not supported in renderToString'` if the evaluated result is not a primitive string [src/jsx/dom/server.ts:26-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L26-L28). Sources: [src/jsx/dom/server.ts:26-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L26-L28)] ### DOM Error Boundaries, Suspense, and Context Specialized components for the DOM runtime handle asynchronous operations, boundary error trapping, and state context propagation [[src/jsx/dom/components.ts:7-38], [src/jsx/dom/context.ts:7-51]]. The `ErrorBoundary` component attaches a `DOM_ERROR_HANDLER` property to fragment nodes that intercepts errors, invokes optional `onError` callbacks, and returns fallback UI via `fallbackRender` or `fallback` props [src/jsx/dom/components.ts:7-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts#L7-L23). The `Suspense` component attaches a handler that checks whether caught errors are instances of `Promise`; if not, they are rethrown, otherwise `err.finally(retry)` is scheduled and the fallback child is returned [src/jsx/dom/components.ts:25-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts#L25-L38). ```typescript export const ErrorBoundary: FC< PropsWithChildren<{ fallback?: Child fallbackRender?: FallbackRender onError?: ErrorHandler }> > = (({ children, fallback, fallbackRender, onError }: any) => { const res = Fragment({ children }) ;(res as any)[DOM_ERROR_HANDLER] = (err: any) => { if (err instanceof Promise) { throw err } onError?.(err) return fallbackRender?.(err) || fallback } return res }) as any export const Suspense: FC> = (({ children, fallback, }: any) => { const res = Fragment({ children }) ;(res as any)[DOM_ERROR_HANDLER] = (err: any, retry: () => void) => { if (!(err instanceof Promise)) { throw err } err.finally(retry) return fallback } return res }) as any ``` Sources: [src/jsx/dom/components.ts:7-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts#L7-L38) Context providers use `createContextProviderFunction` to push and pop context values into an internal array during tree traversal [src/jsx/dom/context.ts:7-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts#L7-L43). When rendering, the provider injects internal tag nodes that mutate the shared values array before and after evaluating children, and registers an error handler to pop values if rendering throws [src/jsx/dom/context.ts:17-42](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts#L17-L42). The `createContext` function initializes the default value array, binds `Provider`, and registers the context inside `globalContexts` [src/jsx/dom/context.ts:45-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts#L45-L51). ```typescript export const createContextProviderFunction = (values: T[]): Function => ({ value, children }: { value: T; children: Child[] }) => { if (!children) { return undefined } // eslint-disable-next-line @typescript-eslint/no-explicit-any const props: { children: any } = { children: [ { tag: setInternalTagFlag(() => { values.push(value) }), props: {}, }, ], } if (Array.isArray(children)) { props.children.push(...children.flat()) } else { props.children.push(children) } props.children.push({ tag: setInternalTagFlag(() => { values.pop() }), props: {}, }) const res = { tag: '', props, type: '' } // eslint-disable-next-line @typescript-eslint/no-explicit-any ;(res as any)[DOM_ERROR_HANDLER] = (err: unknown) => { values.pop() throw err } return res } ``` Sources: [src/jsx/dom/context.ts:7-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts#L7-L43) ## Related - [JSX Components and Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-components-and-context) - [JSX Streaming and Suspense](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-streaming-and-suspense) - [Client DOM and Hooks](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/client-dom-and-hooks) --- ## Technical docs: JSX Components and Context URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-components-and-context
Relevant source files The following files were used as context for generating this wiki page: - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/jsx/dom/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts) - [src/jsx/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts) - [src/jsx/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts) - [src/jsx/dom/render.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/render.ts) - [src/jsx/base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts) - [src/jsx/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts) - [src/jsx/jsx-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts) - [src/jsx/streaming.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts) - [src/jsx/hooks/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/hooks/index.ts) - [src/jsx/intrinsic-elements.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-elements.ts) - [src/jsx/dom/jsx-dev-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-dev-runtime.ts) - [src/jsx/jsx-dev-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-dev-runtime.ts) - [src/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/context.ts) - [src/jsx/dom/context.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts) - [src/jsx/dom/hooks/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/hooks/index.ts) - [src/jsx/dom/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts) - [src/jsx/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/index.ts) - [src/jsx/dom/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/index.ts) - [src/jsx/dom/client.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/client.ts) - [src/jsx/dom/css.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/css.ts) - [src/jsx/dom/jsx-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-runtime.ts) - [src/jsx/intrinsic-element/common.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/common.ts) - [src/jsx/constants.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/constants.ts) - [src/jsx/dom/utils.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/utils.ts) - [package.json](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/package.json) - [src/jsx/types.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/types.ts) - [src/helper/html/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/html/index.ts) - [src/utils/html.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/html.ts)
## Overview Hono's JSX implementation bridges server-side rendering, streaming, and client DOM interaction [JSX Runtime](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-runtime), [Client DOM and Hooks](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/client-dom-and-hooks), [JSX Streaming and Suspense](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-streaming-and-suspense). It provides robust APIs for component hierarchy management, context sharing, document head control, and middleware-driven layout rendering across modern edge and browser runtimes [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context). Sources: [src/jsx/context.ts:8-50](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts#L8-L50), [src/middleware/jsx-renderer/index.ts:15-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L15-L129), [src/jsx/dom/intrinsic-element/components.ts:257-315](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts#L257-L315) ## Context Creation and Propagation Across Runtimes ### API Mechanics and Runtime Differentiation Hono manages context sharing through `createContext`, `Context.Provider`, and `useContext`, implemented separately for server string rendering and client-side DOM reconciliation. The `Context` interface extends component types with a `values` array holding active context states and a `Provider` property pointing to the context itself. When initialized via `createContext(defaultValue: T)`, it registers the context instance in the `globalContexts` array. Sources: [src/jsx/context.ts:8-14](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts#L8-L14), [src/jsx/context.ts:41-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts#L41-L47), [src/jsx/dom/context.ts:45-51](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts#L45-L51) | Runtime Environment | Implementation Target | Provider Mechanism | Error / Cleanup Handling | | :--- | :--- | :--- | :--- | | Server (`src/jsx/context.ts`) | `FC>` | Pushes to `values`, stringifies children, pops in `finally` / `catch`. | `try...catch` pops value on synchronous exception; `.finally()` pops on promises. | | Client DOM (`src/jsx/dom/context.ts`) | `Function` (`createContextProviderFunction`) | Injects internal tag functions before and after child nodes to push/pop values. | `DOM_ERROR_HANDLER` pops value and rethrows error during DOM reconciliation. | Sources: [src/jsx/context.ts:17-40](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts#L17-L40), [src/jsx/dom/context.ts:7-43](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/context.ts#L7-L43) > [!NOTE] > In the server runtime, asynchronous children returning a `Promise` keep the context value active until settled. The `.finally()` handler ensures `values.pop()` executes whether the promise resolves or rejects, preventing stack corruption across concurrent requests. Sources: [src/jsx/context.ts:32-35](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts#L32-L35) ### Consumption and Value Resolution Consuming context values relies on `useContext`, which inspects the last element of the context's `values` stack via `.at(-1)`. Because nested providers push new entries onto the `values` array, `useContext` naturally retrieves the innermost provider's value. ```typescript export const useContext = (context: Context): T => { return context.values.at(-1) as T } ``` Sources: [src/jsx/context.ts:52-54](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts#L52-L54) > [!WARNING] > Modifying or mutating the `values` array directly outside of provider lifecycle execution corrupts context resolution for subsequent renders, especially in shared server runtimes where `globalContexts` retains references across requests. Sources: [src/jsx/context.ts:13-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/context.ts#L13-L16) ## Error Handling with ErrorBoundary ### Error Capture and Fallback Resolution Hono provides `ErrorBoundary` components to intercept errors during server-side rendering and client-side DOM reconciliation[JSX Runtime](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-runtime), [Client DOM and Hooks](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/client-dom-and-hooks). On the server, `ErrorBoundary` accepts `fallback`, `fallbackRender`, and `onError` properties, mapping child components while monitoring for exceptions during early resolution and promise settlement [src/jsx/components.ts:52-58](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts#L52-L58). When an error is thrown, the component invokes `resolveFallbackStr` to process string or asynchronous fallback content [src/jsx/components.ts:70-81](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts#L70-L81). ```typescript const resolveFallbackStr = async () => { const awaitedFallback = await fallback if (typeof awaitedFallback === 'string') { fallbackStr = awaitedFallback } else { fallbackStr = await awaitedFallback?.toString() if (typeof fallbackStr === 'string') { // should not apply `raw` if fallbackStr is undefined, null, or boolean fallbackStr = raw(fallbackStr) } } } ``` Sources: [src/jsx/components.ts:70-81](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts#L70-L81) The server execution call-chain for fallback text processing proceeds through specific internal helpers: 1. `ErrorBoundary` intercepts the component error [src/jsx/components.ts:92-98](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts#L92-L98). 2. `resolveFallbackStr` awaits the fallback value and prepares its string representation [src/jsx/components.ts:70-81](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts#L70-L81). 3. `raw` wraps the resulting string with HTML-escaped flags when valid [src/jsx/components.ts:78](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts#L78). ```mermaid sequenceDiagram participant ErrorBoundary as ErrorBoundary (src/jsx/components.ts) participant resolveFallbackStr as resolveFallbackStr (src/jsx/components.ts) participant raw as raw (src/utils/html.ts) ErrorBoundary->>resolveFallbackStr: Await and inspect fallback prop resolveFallbackStr->>raw: Wrap string fallback with escape metadata ``` Sources: [src/jsx/components.ts:52-81](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts#L52-L81), [src/utils/html.ts:40-46](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/html.ts#L40-L46) > [!NOTE] > If a fallback prop is a promise or contains asynchronous children, `ErrorBoundary` defers rendering error templates until resolution fails, injecting script targets (`data-hono-target`) to swap placeholder templates on the client. Sources: [src/jsx/components.ts:102-128](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts#L102-L128) ### Client DOM Error Boundaries In browser environments, the DOM implementation of `ErrorBoundary` attaches an error handler symbol (`DOM_ERROR_HANDLER`) to rendered fragment nodes [src/jsx/dom/components.ts:7-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts#L7-L23). ```typescript > = (({ children, fallback, fallbackRender, onError }: any) => { const res = Fragment({ children }) ;(res as any)[DOM_ERROR_HANDLER] = (err: any) => { if (err instanceof Promise) { throw err } onError?.(err) return fallbackRender?.(err) || fallback } return res }) as any ``` Sources: [src/jsx/dom/components.ts:13-23](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts#L13-L23) | Symbol Constant | File Origin | Target Purpose | | :--- | :--- | :--- | | `DOM_RENDERER` | `src/jsx/constants.ts:1` | Identifies primary node render functions. | | `DOM_ERROR_HANDLER` | `src/jsx/constants.ts:2` | Assigns catch handlers to fragments for error recovery. | | `DOM_STASH` | `src/jsx/constants.ts:3` | Stores hook state arrays for client components. | | `DOM_INTERNAL_TAG` | `src/jsx/constants.ts:4` | Marks internal wrapper elements during reconciliation. | Sources: [src/jsx/constants.ts:1-4](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/constants.ts#L1-L4) > [!WARNING] > Non-promise errors thrown inside client DOM `ErrorBoundary` nodes invoke `onError` and immediately return `fallbackRender` or `fallback`, whereas promise rejections are rethrown to trigger suspense fallback handling [src/jsx/dom/components.ts:15-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts#L15-L21). Sources: [src/jsx/dom/components.ts:15-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts#L15-L21) ## Document Metadata and Intrinsic Component Hoisting ### Deduplication Keys and Strategy Hono manages document metadata elements—such as `title`, `meta`, `link`, `script`, and `style`—through specialized component wrappers that support server-side hoisting and deduplication [src/jsx/intrinsic-element/common.ts:3-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/common.ts#L3-L9). The deduplication configuration relies on mapping intrinsic tag names to keys used for uniqueness checks during stream serialization [src/jsx/intrinsic-element/common.ts:3-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/common.ts#L3-L9). ```typescript export const deDupeKeyMap: Record = { title: [], script: ['src'], style: ['data-href'], link: ['href'], meta: ['name', 'httpEquiv', 'charset', 'itemProp'], } ``` Sources: [src/jsx/intrinsic-element/common.ts:3-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/common.ts#L3-L9) | Intrinsic Tag | Deduplication Key(s) | Sorting Behavior | | :--- | :--- | :--- | | `title` | `[]` (none) | Unsorted | | `script` | `['src']` | Unsorted | | `style` | `['data-href']` | Sorted via `data-precedence` | | `link` | `['href']` | Sorted if stylesheet with precedence | | `meta` | `['name', 'httpEquiv', 'charset', 'itemProp']` | Unsorted | Sources: [src/jsx/intrinsic-element/common.ts:3-9](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/common.ts#L3-L9), [src/jsx/intrinsic-element/components.ts:101-105](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L101-L105) > [!NOTE] > If a `meta` tag includes an `itemProp` attribute, it bypasses hoisting logic entirely and renders immediately without deduplication [src/jsx/intrinsic-element/components.ts:97-99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L97-L99). Sources: [src/jsx/intrinsic-element/components.ts:97-99](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L97-L99) ### Server-Side Hoisting and Stream Injection During server rendering, `documentMetadataTag` intercepts metadata nodes, generates their string representations, and attaches an `HtmlEscapedCallback` via `insertIntoHead` [src/jsx/intrinsic-element/components.ts:96-119](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L96-L119). When the HTML stream buffer encounters the `` closing tag, accumulated metadata items are deduplicated against recorded maps and injected directly before the tag [src/jsx/intrinsic-element/components.ts:21-91](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L21-L91). ```typescript let duped = false const deDupeKeys = deDupeKeyMap[tagName] const deDupeByKey = shouldDeDupeByKey(tagName, precedence !== undefined) if (deDupeByKey) { LOOP: for (const [, tagProps] of tags) { if ( tagName === 'link' && !(tagProps.rel === 'stylesheet' && tagProps[dataPrecedenceAttr] !== undefined) ) { continue } for (const key of deDupeKeys) { if ((tagProps?.[key] ?? null) === props?.[key]) { duped = true break LOOP } } } } ``` Sources: [src/jsx/intrinsic-element/components.ts:36-54](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L36-L54) Stylesheets with precedence attributes utilize `dataPrecedenceAttr` (`data-precedence`) to order style and link elements within the head block based on unique precedence strings [src/jsx/intrinsic-element/common.ts:13-16](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/common.ts#L13-L16), [src/jsx/intrinsic-element/components.ts:66-81](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L66-L81). > [!WARNING] > Link elements lacking a stylesheet relationship, or containing explicit `onLoad` or `onError` handlers, skip server-side head hoisting and fall back to standard inline rendering [src/jsx/intrinsic-element/components.ts:163-168](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L163-L168). Sources: [src/jsx/intrinsic-element/components.ts:163-168](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L163-L168) ## Component Tree Rendering with JSX Renderer Middleware ### Setup and Configuration The `jsxRenderer` middleware intercepts Hono requests to inject layout wrappers, provide a request context via `RequestContext`, and configure response serialization [src/middleware/jsx-renderer/index.ts:116-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L116-L129). It accepts an optional `component` layout function and an `options` object or factory callback defining `docType` and `stream` behavior [src/middleware/jsx-renderer/index.ts:33-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L33-L38). ```typescript type RendererOptions = { docType?: boolean | string stream?: boolean | Record } ``` Sources: [src/middleware/jsx-renderer/index.ts:18-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L18-L21) | Option Key | Type | Default Value | Purpose | | :--- | :--- | :--- | :--- | | `docType` | `boolean \| string` | `true` (``) | Prepends a document type string or suppresses it when set to `false` [[src/middleware/jsx-renderer/index.ts:19` | [src/middleware/jsx-renderer/index.ts:42-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L42-L47)], | | `stream` | `boolean \| Record` | `false` | Enables chunked HTML streaming response or custom stream headers [[src/middleware/jsx-renderer/index.ts:20` | [src/middleware/jsx-renderer/index.ts:66-75](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L66-L75)] | Sources: [src/middleware/jsx-renderer/index.ts:18-21](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L18-L21), [src/middleware/jsx-renderer/index.ts:42-47](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L42-L47), [src/middleware/jsx-renderer/index.ts:66-75](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L66-L75) > [!NOTE] > When `options.stream` is set to `true`, the middleware automatically sets standard headers including `Transfer-Encoding: chunked`, `Content-Type: text/html; charset=UTF-8`, and `Content-Encoding: Identity` [src/middleware/jsx-renderer/index.ts:67-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L67-L70). Sources: [src/middleware/jsx-renderer/index.ts:67-70](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L67-L70) ### Call-Chain Execution Walkthrough When `c.render()` is invoked during request handling, execution flows through the renderer generation phase down to template evaluation and callback resolution. 1. `jsxRenderer` — Registers the layout wrapper and assigns the renderer function generated by `createRenderer` to the context [src/middleware/jsx-renderer/index.ts:116-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L116-L129). Sources: [src/middleware/jsx-renderer/index.ts:116-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L116-L129) 2. `createRenderer` — Resolves options, wraps the layout component with user children inside a `RequestContext.Provider`, and delegates to either `renderToReadableStream` or `c.html` [src/middleware/jsx-renderer/index.ts:33-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L33-L80). Sources: [src/middleware/jsx-renderer/index.ts:33-80](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L33-L80) 3. `html` — Parses template strings and values into a buffer, handling raw injection and deferred callbacks [src/helper/html/index.ts:11-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/html/index.ts#L11-L56). Sources: [src/helper/html/index.ts:11-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/html/index.ts#L11-L56) 4. `resolveCallbackSync` — Iterates through any registered `HtmlEscapedCallback` functions at the stringify phase to finalize output buffer content [src/utils/html.ts:129-140](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/html.ts#L129-L140). Sources: [src/utils/html.ts:129-140](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/html.ts#L129-L140) ```mermaid sequenceDiagram participant Middleware as jsxRenderer participant Renderer as createRenderer participant HtmlHelper as html participant Callback as resolveCallbackSync Middleware->>Renderer: c.setRenderer(...) Renderer->>HtmlHelper: html`${raw(docType)}${jsx(...)}` HtmlHelper->>Callback: resolveCallbackSync(...) ``` Sources: [src/middleware/jsx-renderer/index.ts:33-129](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L33-L129), [src/helper/html/index.ts:11-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/html/index.ts#L11-L56), [src/utils/html.ts:129-140](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/html.ts#L129-L140) > [!WARNING] > Attempting to call `useRequestContext()` outside of a tree wrapped by `RequestContext` throws an error stating that `RequestContext is not provided` [src/middleware/jsx-renderer/index.ts:155-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L155-L164). Sources: [src/middleware/jsx-renderer/index.ts:155-164](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts#L155-L164) ## Form Handling and Action Integration ### Client-Side Form Action Dispatch Client-side form handling supports action functions by wrapping intrinsic `form` elements with a `FormContext` provider and intercepting submit events. When a submit event occurs on a trusted event, the handler extracts form data using `FormData`, updates the state with pending data and dirtiness flags, and executes the provided action function. If the action function returns a promise, it registers the action and awaits its completion before resetting the form state. ```typescript const [state, setState] = useState<[FormData | null, boolean]>([null, false]) const onSubmit = useCallback<(ev: SubmitEvent | CustomEvent) => void>( async (ev: SubmitEvent | CustomEvent) => { const currentAction = ev.isTrusted ? action : (ev as CustomEvent).detail[customEventFormAction] if (typeof currentAction !== 'function') { return } ev.preventDefault() const formData = new FormData(ev.target as HTMLFormElement) setState([formData, true]) const actionRes = currentAction(formData) if (actionRes instanceof Promise) { registerAction(actionRes) await actionRes } setState([null, true]) }, [] ) ``` Sources: [src/jsx/dom/intrinsic-element/components.ts:332-353](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts#L332-L353) > [!NOTE] > Form-actionable elements such as submit buttons intercept click events when a `formAction` function is supplied, preventing default navigation and dispatching a custom `submit` event carrying the action reference via `customEventFormAction`. > Sources: [src/jsx/dom/intrinsic-element/components.ts:388-405](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts#L388-L405) ### Server-Side Permalink Resolution On the server side, intrinsic `form` components inspect the `action` property to verify if it is a function. If the action function contains a `PERMALINK` symbol attached to it, the action is transformed into its corresponding string permalink route for static or server-rendered markup generation. ```typescript export const form: FC< PropsWithChildren<{ action?: Function | string method?: 'get' | 'post' }> > = (props) => { if (typeof props.action === 'function') { props.action = PERMALINK in props.action ? (props.action[PERMALINK] as string) : undefined } ``` Sources: [src/jsx/intrinsic-element/components.ts:182-190](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L182-L190) > [!WARNING] > Passing a function as a form action without an associated `PERMALINK` symbol during server-side rendering results in an undefined action attribute value. > Sources: [src/jsx/intrinsic-element/components.ts:188-190](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts#L188-L190) ## Related - [JSX Runtime](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-runtime) - [JSX Streaming and Suspense](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-streaming-and-suspense) --- ## Technical docs: JSX Streaming and Suspense URL: https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/jsx-and-ui/jsx-streaming-and-suspense
Relevant source files The following files were used as context for generating this wiki page: - [src/jsx/streaming.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts) - [src/jsx/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/components.ts) - [src/jsx/dom/render.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/render.ts) - [src/jsx/dom/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts) - [src/jsx/dom/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/intrinsic-element/components.ts) - [src/jsx/dom/server.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts) - [src/jsx/intrinsic-element/components.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/components.ts) - [src/jsx/hooks/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/hooks/index.ts) - [src/helper/streaming/sse.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/sse.ts) - [src/jsx/jsx-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-runtime.ts) - [src/jsx/base.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/base.ts) - [src/middleware/jsx-renderer/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/jsx-renderer/index.ts) - [src/helper/streaming/text.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/text.ts) - [src/helper/streaming/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/streaming/stream.ts) - [src/jsx/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/index.ts) - [src/jsx/dom/hooks/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/hooks/index.ts) - [src/jsx/dom/index.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/index.ts) - [src/jsx/dom/client.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/client.ts) - [src/jsx/jsx-dev-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/jsx-dev-runtime.ts) - [src/utils/stream.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/stream.ts) - [src/utils/html.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/utils/html.ts) - [src/middleware/etag/digest.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/middleware/etag/digest.ts) - [src/jsx/constants.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/constants.ts) - [src/jsx/dom/jsx-dev-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-dev-runtime.ts) - [runtime-tests/lambda/stream-mock.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/lambda/stream-mock.ts) - [src/jsx/dom/jsx-runtime.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/jsx-runtime.ts) - [src/jsx/intrinsic-elements.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-elements.ts) - [src/adapter/cloudflare-workers/utils.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/adapter/cloudflare-workers/utils.ts) - [runtime-tests/lambda/mock.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/runtime-tests/lambda/mock.ts) - [src/jsx/intrinsic-element/common.ts](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/intrinsic-element/common.ts)
## Overview Hono provides experimental JSX streaming and Suspense capabilities via `renderToReadableStream` and the `Suspense` component, enabling server-rendered HTML chunks to be flushed progressively to clients. By resolving asynchronous child nodes and callbacks across execution phases, it allows fallback content placeholders to be emitted immediately while pending components resolve out-of-order. Sources: [src/jsx/streaming.ts:42-133](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L42-L133), [src/jsx/streaming.ts:142-201](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L142-L201) ## Stream Generation and ReadableStream Pipeline Hono exposes stream generation functions across both core JSX modules and React DOM server compatibility layers. The primary streaming entry point is `renderToReadableStream`, defined in `src/jsx/streaming.ts`, which accepts an initial content payload and an optional error handler before constructing a standard `ReadableStream` instance. The `hono/jsx/server` module (`src/jsx/dom/server.ts`) re-exports an asynchronous variant of `renderToReadableStream` that delegates directly to the core streaming implementation while parsing configuration options such as `onError`. ```typescript export const renderToReadableStream = ( content: HtmlEscapedString | JSXNode | Promise, onError: (e: unknown) => string | void = console.trace ): ReadableStream => { let cancelled = false const reader = new ReadableStream({ async start(controller) { try { if (content instanceof JSXNode) { content = content.toString() as HtmlEscapedString | Promise } const context = typeof content === 'object' ? content : {} const resolved = await resolveCallback( content, HtmlEscapedCallbackPhase.BeforeStream, true, context ) if (!cancelled) { controller.enqueue(textEncoder.encode(resolved)) } // ... ``` Sources: [src/jsx/streaming.ts:142-163](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L142-L163) The pipeline transforms JSX nodes, escaped strings, or promises into binary chunks using a `TextEncoder` instance. When `renderToReadableStream` initializes, it checks whether the content parameter is an instance of `JSXNode`, invoking its `.toString()` method to yield an escaped string or promise. It then resolves callbacks through `HtmlEscapedCallbackPhase.BeforeStream` before enqueuing the encoded byte array into the readable stream controller. | Function / Module | Target Runtime / API | Parameters | Return Type | | :--- | :--- | :--- | :--- | | `renderToReadableStream` (`src/jsx/streaming.ts`) | Core Hono JSX Streaming | `content`, `onError` | `ReadableStream` | | `renderToReadableStream` (`src/jsx/dom/server.ts`) | React DOM Server Compatibility | `element`, `options` | `Promise>` | | `renderToString` (`src/jsx/dom/server.ts`) | Synchronous DOM Server | `element`, `options` | `string` | Sources: [src/jsx/streaming.ts:142-145](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L142-L145), [src/jsx/dom/server.ts:21-30](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L21-L30), [src/jsx/dom/server.ts:50-63](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L50-L63) > [!NOTE] > Options passed to `renderToReadableStream` in `hono/jsx/server` other than `onError` (such as `identifierPrefix`, `namespaceURI`, `nonce`, `bootstrapScripts`, and `progressiveChunkSize`) trigger a console warning stating that those options are not supported yet. Sources: [src/jsx/dom/server.ts:54-56](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L54-L56) > [!WARNING] > Synchronous rendering via `renderToString` in `hono/jsx/server` throws an error if an asynchronous component is encountered, as async components cannot be resolved without a Promise-based [execution context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/core-engine/execution-context). Sources: [src/jsx/dom/server.ts:26-28](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/server.ts#L26-L28) ## Suspense Architecture and Placeholder Inlining ### Component Structure and Context Resolution The `Suspense` component in `src/jsx/streaming.ts` acts as an asynchronous boundary resolver for JSX tree rendering. When evaluated, it wraps child elements and checks context for script nonces if provided through custom providers or context maps. Children passed to `Suspense` are normalized into an array, and the component initializes a data stack node utilizing `DOM_STASH` to support the execution of hooks and asynchronous boundaries. ```typescript const stackNode = { [DOM_STASH]: [0, []] } as unknown as NodeObject const popNodeStack = (value?: unknown) => { buildDataStack.pop() return value } ``` Sources: [src/jsx/streaming.ts:55-59](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L55-L59) ### Fallback Marker Emission and Promise Detection During synchronous child stringification, if a child evaluation throws a `Promise` (triggered by an asynchronous component or data-fetching hook), the `Suspense` boundary captures the promise and switches into streaming mode. ```typescript try { stackNode[DOM_STASH][0] = 0 buildDataStack.push([[], stackNode]) resArray = children.map((c) => c == null || typeof c === 'boolean' ? '' : c.toString() ) as HtmlEscapedString[] } catch (e) { if (e instanceof Promise) { resArray = [ e.then(() => { stackNode[DOM_STASH][0] = 0 buildDataStack.push([[], stackNode]) return childrenToString(children as Child[]).then(popNodeStack) }), ] as Promise[] } else { throw e } } finally { popNodeStack() } ``` Sources: [src/jsx/streaming.ts:61-81](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L61-L81) When asynchronous promises are detected in `resArray`, a unique numeric identifier is assigned using the module-level `suspenseCounter`. The fallback content is serialized and wrapped in an HTML comment boundary and a template anchor tag using the format `${fallbackStr}`. ```typescript if (resArray.some((res) => (res as {}) instanceof Promise)) { const index = suspenseCounter++ const fallbackStr = await fallback.toString() return raw(`${fallbackStr}`, [ ...(fallbackStr.callbacks || []), ({ phase, buffer, context }) => { // ... ``` Sources: [src/jsx/streaming.ts:83-88](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L83-L88) > [!NOTE] > If all child nodes resolve synchronously without throwing a `Promise`, `Suspense` bypasses streaming mechanics entirely, returning the concatenated string result via `raw(resArray.join(''))`. Sources: [src/jsx/streaming.ts:130-132](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L130-L132) > [!WARNING] > The DOM-specific counterpart `Suspense` exported from `src/jsx/dom/components.ts` registers a `DOM_ERROR_HANDLER` that catches promise rejections differently, attaching a `.finally(retry)` hook for client-side DOM reconciliation rather than server-side template streaming. Sources: [src/jsx/dom/components.ts:25-38](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/dom/components.ts#L25-L38) ## Out-of-Order Chunk Resolution and Replacement ### Callback Phases and Stream Buffering When asynchronous promises within a `Suspense` boundary complete, the callback mechanism handles chunk resolution based on the `HtmlEscapedCallbackPhase`. During the initial `BeforeStream` phase, callbacks return early without altering the stream output. Once the stream begins, `Promise.all(resArray)` resolves all pending asynchronous children, flattening the resulting HTML array into a unified string. ```typescript return Promise.all(resArray).then(async (htmlArray) => { htmlArray = htmlArray.flat() const content = htmlArray.join('') if (buffer) { buffer[0] = buffer[0].replace( new RegExp(`.*?`), content ) } ``` Sources: [src/jsx/streaming.ts:92-100](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L92-L100) If an active chunk buffer exists (`buffer`), the runtime replaces the placeholder region—bounded by `` and the closing comment ``—directly within the buffered content string. When no buffer is present, the resolved content is wrapped in a target template and paired with an inline swapping script for client-side insertion. > [!NOTE] > The buffer check allows server-side renderers to catch up and inline resolved components directly into preceding stream chunks if resolution finishes before the chunk is flushed to the network controller. Sources: [src/jsx/streaming.ts:95-103](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L95-L103) ### Client-Side DOM Swapping Scripts When streaming responses without an active pre-buffer, Hono injects an IIFE execution script immediately following the resolved chunk container. This script locates the placeholder anchor via `document.getElementById('H:${index}')`, traverses sibling nodes up to the closing comment boundary (`/^\$/`), and replaces the fallback content with the new template content. ```typescript let html = buffer ? '' : ` ((d,c,n) => { c=d.currentScript.previousSibling d=d.getElementById('H:${index}') if(!d)return do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$') d.replaceWith(c.content) })(document) ` ``` Sources: [src/jsx/streaming.ts:101-113](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/jsx/streaming.ts#L101-L113) > [!WARNING] > If a script nonce is resolved from context and configured, it is appended directly to the injected `` if (buffer) { buffer[0] = `${appendStyleScript}${buffer[0]}` return } return Promise.resolve(appendStyleScript) } ``` Sources: [src/helper/css/index.ts:109-121](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/css/index.ts#L109-L121) > [!WARNING] > If a style element matching the context identifier is not present in the render buffer when styles flush, Hono falls back to injecting an inline script containing a DOM query selector fallback. This requires client-side JavaScript execution to populate the stylesheet dynamically. Sources: [src/helper/css/index.ts:110-121](https://github.com/blade47/hono/blob/e50df01453e71b071c3e6136b161b160b9fdf916/src/helper/css/index.ts#L110-L121) ## Client DOM Stylesheet Insertion ### Stylesheet Discovery and Rule Splitting The browser-side CSS subsystem initializes via `createCssJsxDomObjects`, which accepts an identifier to locate the corresponding `