Relevant source files
The following files were used as context for generating this wiki page:
- src/index.ts
- package.json
- src/preset/quick.ts
- runtime-tests/workerd/index.ts
- src/hono-base.ts
- src/middleware/ip-restriction/index.ts
- jsr.json
- src/adapter/lambda-edge/handler.ts
- src/adapter/aws-lambda/handler.ts
- src/adapter/cloudflare-pages/index.ts
- src/router/linear-router/index.ts
- src/adapter/netlify/index.ts
- src/helper/dev/index.ts
- src/adapter/cloudflare-pages/handler.ts
- src/adapter/netlify/handler.ts
- src/hono.ts
- src/router/smart-router/index.ts
- src/adapter/deno/index.ts
- src/preset/tiny.ts
- src/adapter/service-worker/index.ts
- src/adapter/vercel/index.ts
- src/context.ts
- src/adapter/vercel/handler.ts
- src/adapter/bun/index.ts
- src/adapter/aws-lambda/index.ts
- src/helper/adapter/index.ts
- src/adapter/cloudflare-workers/index.ts
- src/adapter/lambda-edge/index.ts
- src/helper/ssg/index.ts
- 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 and Execution Context modules, exporting a default fetch handler or entry point. Runtime-specific execution details are bridged through dedicated 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
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.
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hono!'))
export default appSources: src/index.ts:7-14
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
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
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 Sources: src/helper/adapter/index.ts:50-90
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
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.
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 appSources: runtime-tests/workerd/index.ts:2-13
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
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.
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
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
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 Sources: src/adapter/lambda-edge/handler.ts:69-79 Sources: src/adapter/lambda-edge/handler.ts:88-99
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
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.
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
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
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 Sources: src/adapter/cloudflare-pages/handler.ts:49-59 Sources: src/adapter/cloudflare-pages/handler.ts:114-115 Sources: src/adapter/vercel/handler.ts:4-6
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
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
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 Sources: src/router/pattern-router/index.ts:1-6
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
Related
On This Page
OverviewMinimal Web Standard Application SetupCore Application Entry PointExported Public Types and ClassesHandling Requests Across EnvironmentsRuntime Identification and Environment AccessPortable Environment Variable RetrievalConfiguring Serverless AWS Lambda HandlersStandard Lambda Events and Function HandlersLambda@Edge Event ProcessingDeploying on Edge Cloud HandlersCloudflare Pages Request and Middleware HandlersStatic Asset Serving and Vercel IntegrationSelecting Lightweight Router EnginesAlternative Routing ModulesRouter Class ArchitectureRelated