Relevant source files
The following files were used as context for generating this wiki page:
- src/hono-base.ts
- src/request.ts
- src/context.ts
- src/adapter/netlify/handler.ts
- src/adapter/aws-lambda/handler.ts
- src/types.ts
- src/helper/streaming/sse.ts
- src/adapter/vercel/handler.ts
- src/router/reg-exp-router/prepared-router.ts
- src/adapter/lambda-edge/handler.ts
- src/helper/proxy/index.ts
- src/client/client.ts
- src/adapter/cloudflare-pages/handler.ts
- src/helper/streaming/stream.ts
- src/router/linear-router/router.ts
- src/client/fetch-result-please.ts
- src/adapter/service-worker/index.ts
- src/adapter/cloudflare-workers/websocket.ts
- src/middleware/serve-static/index.ts
- src/adapter/service-worker/handler.ts
- src/router/pattern-router/router.ts
- runtime-tests/workerd/index.ts
- src/http-exception.ts
- 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, src/request.ts:51-80, src/request.ts:106-128, src/request.ts:220-239, src/adapter/aws-lambda/handler.ts:318-342, src/http-exception.ts:66-77
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.
export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {
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
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
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. |
export const GET_MATCH_RESULT: unique symbol = Symbol()Sources: src/request/constants.ts:1-1
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.
type Body = {
json: any
text: string
arrayBuffer: ArrayBuffer
blob: Blob
formData: FormData
}
type BodyCache = Partial<Body>Sources: src/request.ts:20-27
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, src/request.ts:220-239
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.
#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<BodyInit>).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
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
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<T>() | Promise<T> | Retrieves cached text via #cachedBody('text') and parses it with JSON.parse. |
text() | Promise<string> | Invokes #cachedBody('text') to consume the raw stream as a string. |
parseBody() | Promise<T> | Delegates to the parseBody utility function supporting multipart/form-data and application/x-www-form-urlencoded. |
json<T = any>(): Promise<T> {
return this.#cachedBody('text').then((text: string) => JSON.parse(text))
}
text(): Promise<string> {
return this.#cachedBody('text')
}
async parseBody(options?: Partial<ParseBodyOptions>) {
return parseBody(this, options)
}Sources: src/request.ts:212-218, src/request.ts:253-271
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().
param<P2 extends ParamKeys<P> = ParamKeys<P>>(
key: string extends P ? never : P2 extends `${infer _}?` ? never : P2
): string
param<P2 extends RemoveQuestion<ParamKeys<P>> = RemoveQuestion<ParamKeys<P>>>(
key: P2
): string | undefined
param(key: string): string | undefined
param<P2 extends string = P>(): Simplify<UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>>
param(key?: string): unknown {
return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams()
}Sources: src/request.ts:94-104
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
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.
#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<string, string> {
const decoded: Record<string, string> = {}
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
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<string, string> | 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<string, string[]> | getQueryParams(this.url, key) | Retrieves all query parameter values as string arrays or a dictionary mapping keys to string arrays. |
query(key: string): string | undefined
query(): Record<string, string>
query(key?: string) {
return getQueryParam(this.url, key)
}
queries(key: string): string[] | undefined
queries(): Record<string, string[]>
queries(key?: string) {
return getQueryParams(this.url, key)
}Sources: src/request.ts:148-171
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.
export class EventV2Processor extends EventProcessor<APIGatewayProxyEventV2> {
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, src/adapter/lambda-edge/handler.ts:152-184
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
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 and executing a fallback fetch to opts.fetch when a response yields a 404 Not Found status.
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, src/adapter/service-worker/handler.ts:18-36
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) |
export const handle = (
app: Hono<any, any>
): ((req: Request, context: any) => Response | Promise<Response>) => {
return (req: Request, context: any) => {
return app.fetch(req, { context })
}
}Sources: src/adapter/netlify/handler.ts:4-9, src/adapter/vercel/handler.ts:4-7
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.
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
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, src/http-exception.ts:55-56
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.
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
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, src/helper/proxy/index.ts:160-166
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
| 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, src/helper/proxy/index.ts:80-82
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, src/helper/proxy/index.ts:164
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, src/helper/proxy/index.ts:60-77
const ALLOWED_TOKEN_PATTERN = /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/Sources: src/helper/proxy/index.ts:21-22
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, src/helper/proxy/index.ts:60-77
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
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
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
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
Related
On This Page
OverviewIncoming Web Request EncapsulationRequest Instance WrapperSymbol Constants and MetadataBody Parsing and Stream BufferingLazy Caching and Payload ExtractionBody Extraction FlowSupported Body MethodsParameter and Query ExtractionRoute Parameter ResolutionDecoding and Lookup MechanicsQuery String Extraction HelpersServerless Event AdaptersAWS Lambda and Lambda@Edge ConversionCloudflare Pages and Service WorkersLightweight Platform HandlersHTTP Exception ProcessingHTTPException Class SemanticsResponse Generation and PropagationUpstream Request ForwardingProxy Initialization and Request BuildingHeader Preprocessing and ValidationDispatch and Response SanitizationRelated