Skip to main content
doc0blade47/honodocumentation home
Sign in

Quick Start

Last updated Oct 12, 202691% grounded
Relevant source files

The following files were used as context for generating this wiki page:

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 app

Sources: 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 SymbolCategoryDescription
HonoClassCentral application instance for routing and method registration
ContextClassEncapsulates request, response, and environment bindings
Env, Input, SchemaTypeType definitions for environment bindings and request validation inputs
Handler, MiddlewareHandlerTypeFunction signatures for route handlers and middleware execution
HonoRequestTypeWrapper 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 KeyDetection MechanismEnvironment Source
nodeglobal.process.release.name === 'node' or user agent Node.jsglobal.process.env
denoUser agent DenoDeno.env.toObject()
bunUser agent Bunglobal.process.env
workerdUser agent Cloudflare-Workersc.env (Execution Context bindings)
edge-lightglobal.EdgeRuntime string presenceglobal.process.env
fastlyglobal.fastly definition{} (ConfigStore usage)
otherFallback 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 app

Sources: 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 TypeRecord StructureKey FieldsResult Format
CloudFrontEdgeEventevent.Records[0].cfconfig, request, responseCloudFrontResult
LambdaEventAPIGatewayProxyEventhttpMethod, path, headersAPIGatewayProxyResult
APIGatewayProxyEventV2ApiGatewayRequestContextV2rawPath, rawQueryString, cookiesAPIGatewayProxyResult
ALBProxyEventALBRequestContexthttpMethod, queryStringParametersAPIGatewayProxyResult
LatticeProxyEventV2LatticeRequestContextV2path, method, isBase64EncodedAPIGatewayProxyResult

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 ModuleExported FunctionTarget EnvironmentCore Parameter Structure
hono/cloudflare-pageshandleCloudflare Pagesapp: Hono
hono/cloudflare-pageshandleMiddlewareCloudflare Pages Functionsmiddleware: MiddlewareHandler
hono/cloudflare-pagesserveStaticCloudflare Pages Advanced Modenone
hono/vercelhandleVercel Serverless Functionsapp: 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 ModuleExported ClassPrimary Engine Characteristics
src/router/linear-router/index.tsLinearRouterLinear iteration matching suited for minimal overhead
src/router/smart-router/index.tsSmartRouterDynamic selection router adapting to route patterns
src/router/pattern-router/index.tsPatternRouterPattern-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

Was this page helpful?