Relevant source files
The following files were used as context for generating this wiki page:
- src/index.ts
- src/hono-base.ts
- package.json
- src/types.ts
- src/router/smart-router/index.ts
- src/preset/quick.ts
- src/hono.ts
- src/context.ts
- src/router/linear-router/index.ts
- src/adapter/cloudflare-pages/index.ts
- src/adapter/cloudflare-pages/handler.ts
- src/middleware/jsx-renderer/index.ts
- src/preset/tiny.ts
- runtime-tests/workerd/index.ts
- src/router/pattern-router/index.ts
- src/router/trie-router/index.ts
- jsr.json
- src/adapter/netlify/handler.ts
- src/adapter/vercel/index.ts
- src/adapter/netlify/index.ts
- src/adapter/vercel/handler.ts
- src/adapter/deno/index.ts
- src/helper/ssg/index.ts
- src/adapter/aws-lambda/index.ts
- src/helper/accepts/index.ts
Overview
Hono is a lightweight web framework built natively on Runtime Adapters and Web Standard request-response interfaces src/index.ts:4-4. By exposing modular components through package export maps in Project Structure, it provides unified 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, Trie and Smart Routers, Linear and Pattern Routers, alongside zero-dependency JSX Components and Context and 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, src/hono-base.ts:65, package.json:601-622, src/preset/quick.ts:20-22, src/preset/tiny.ts:18, src/adapter/deno/index.ts:7, src/middleware/jsx-renderer/index.ts:9, src/index.ts:1-53.
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. The core Hono class processes incoming standard requests through a unified Execution Context and dispatches them via modular middleware pipelines src/index.ts:8-14, package.json:601-622.
/**
* @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
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. 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.
| 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, package.json:650-666
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.
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
Export Maps and Subpath Modules
Granular subpath exports in 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 |
./quick | ./src/preset/quick.ts | Optimized preset bundle Presets and Builds |
./bun | ./src/adapter/bun/index.ts | Bun Adapter runtime integration |
./deno | ./src/adapter/deno/index.ts | Deno Adapter runtime integration |
./validator | ./src/validator/index.ts | Request Validation helper |
Sources: package.json:602-606, jsr.json:13-14, jsr.json:57
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 |
src/router/trie-router/index.ts | TrieRouter | Traverses path segments using node trees for hierarchical matching Trie and Smart Routers |
src/router/pattern-router/index.ts | PatternRouter | Executes basic regular expression evaluation for lightweight builds Linear and Pattern Routers |
src/router/linear-router/index.ts | LinearRouter | Performs simple route array scans for minimal bundle overhead Linear and Pattern Routers |
Sources: 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
Heuristic Selection Strategies
The RegExp Router and SmartRouter engine variants evaluate registered route patterns to determine optimal dispatch strategies src/router/smart-router/index.ts:3-6. 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.
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.
Sources: src/router/smart-router/index.ts:1-6
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<Response> |
| Vercel | src/adapter/vercel/handler.ts | handle(app: Hono): (req: Request) => Response | Promise<Response> |
Sources: src/adapter/cloudflare-pages/handler.ts:32-46, src/adapter/netlify/handler.ts:4-9, src/adapter/vercel/handler.ts:4-8
export const handle =
(app: Hono<any, any, any>) =>
(req: Request): Response | Promise<Response> => {
return app.fetch(req)
}Sources: src/adapter/vercel/handler.ts:4-8
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. 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.
export const handle =
<E extends Env = Env, S extends Schema = BlankSchema, BasePath extends string = '/'>(
app: Hono<E, S, BasePath>
): PagesFunction<E['Bindings']> =>
(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
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.
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
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.
| 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, package.json:596-615
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, package.json:697-699
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 |
| What each top-level and source directory in the repository does, and how components like adapters, routers, JSX, and middleware are organized. | Project Structure |
| How the central Hono and HonoBase classes instantiate, manage routing tables, handle sub-app mounting, and expose HTTP method registrations. | Application Core |
| How incoming Web Standard Request objects are received, dispatched through dispatchers, parsed, and converted to Response instances. | Request Lifecycle |
| How the Context class wraps requests, exposes typed parameter/header accessors, manages response rendering, and interacts with environment bindings. | Execution Context |
| How the compose function implements the onion-model middleware chain and handles asynchronous next flow and handler pipeline execution. | Middleware Composition |
| How lightweight and custom distribution bundles like hono/quick and hono/tiny minimize bundle overhead for size-constrained environments. | 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 |
| How Hono's flagship RegExpRouter compiles route trees and wildcards into single regular expressions for ultrafast matching without looping. | 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 |
| How the lightweight LinearRouter and PatternRouter execute simple route array scans or basic regex evaluation for tiny bundles. | Linear and Pattern Routers |
| How Hono adapts to Cloudflare Workers and Cloudflare Pages environments, exposing execution contexts, bindings, and module asset serving. | Runtime Adapters |
| How Hono integrates with Bun's native HTTP server, static file reader, connection info APIs, and native WebSocket implementation. | Bun Adapter |
| How Hono runs on Deno via Deno.serve, mapping connection metadata, static file assets, SSG builds, and Deno WebSockets. | 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 |
| How Hono handles standard HTTP Basic authentication credentials and Bearer token parsing using constant-time buffer comparisons. | 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 |
| How Cross-Site Request Forgery origin checks protect mutating requests and how body-limit middleware prevents payload overflow vulnerabilities. | CSRF and Body Limit |
| How the IP restriction middleware parses, matches, and blocks or allows client IPv4/IPv6 addresses and CIDR subnets. | 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 |
| How the compress middleware uses Accept-Encoding negotiation and Web Streams CompressionStream to encode responses with gzip or deflate. | Response Compression |
| How the logger prints colorized HTTP request traces and how Server-Timing middleware records operational durations for debugging. | 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 |
| How trailing-slash normalization routes URLs cleanly and how method-override supports PUT/DELETE verbs from standard HTML forms. | Trailing Slash and Override |
| How AsyncLocalStorage-backed context-storage enables global access to the current request Context without explicit parameter passing. | Context Storage |
| How Hono's zero-dependency JSX implementation compiles JSX element trees, handles raw HTML strings, and serializes DOM output asynchronously. | 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 |
| How the Suspense component and renderToReadableStream facilitate out-of-order chunked HTML streaming across modern edge runtimes. | 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 |
| How hono/css generates scoped class names, manages style injection, and enables critical CSS extraction for server-rendered and client JSX. | 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 |
| How the validator helper parses and validates JSON, query strings, URL parameters, and forms with third-party schema libraries or custom rules. | Validation |
| How stream, streamText, and streamSSE helpers handle chunked binary/text streams and Server-Sent Events with automatic backpressure. | Streaming and SSE |
| How the createWebSocket helper coordinates full-duplex WebSocket connections across differing runtime engines like Bun, Deno, and Cloudflare. | 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 |
| How serve-static middleware handles path rewriting, MIME type resolution, directory index fallback, and asset streaming across environments. | 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 |
| How low-level shared helpers parse cookies, manage HTML escaping, encode URLs, handle concurrent execution, and resolve HTTP status codes. | Utilities and Encoding |
Related
On This Page
OverviewArchitectural Foundation on Web StandardsCore Web PrimitivesDesign Philosophy and RuntimesPublic Entry Points and PackagingPackage Configuration and DistributionExport Maps and Subpath ModulesConfigurable Router Architecture SelectionRouter Implementations and ModulesHeuristic Selection StrategiesMulti-Runtime Execution Engine CompatibilityAdapter Handler ImplementationsCloudflare Pages and Workerd IntegrationsFramework Integration EcosystemBuild Pipeline and Package ExportsWhere to go nextRelated