---
title: "Request Lifecycle"
description: "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, movin..."
last_updated: "2026-10-12T08:14:12.710392+00:00"
canonical_url: "https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/core-engine/request-lifecycle"
---


## 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.


## 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<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 = {}
  }
...
```

> [!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. |

```typescript
export const GET_MATCH_RESULT: unique symbol = Symbol()
```

## 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<Body>
```

> [!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.

```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<BodyInit>).then((body) => {
        if (anyCachedKey === 'json') {
          body = JSON.stringify(body)
        }
        return new Response(body)[key]()
      })
    }

    return (bodyCache[key] = raw[key]())
  }
```

> [!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`. |

```typescript
  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)
  }
```

## 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<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()
  }
```

> [!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.

```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<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
  }
```

### 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. |

```typescript
  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)
  }
```

## 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<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
  }
...
```

> [!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](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/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 =
  <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: {},
      }
    )
  }
```

### 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<any, any>
): ((req: Request, context: any) => Response | Promise<Response>) => {
  return (req: Request, context: any) => {
    return app.fetch(req, { context })
  }
}
```

## 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
  }
...
```

> [!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.

```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,
    })
  }
}
```

## 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.

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.

| 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 |


> [!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.

```typescript
const ALLOWED_TOKEN_PATTERN = /^[!#$%&'*+\-.0-9A-Z^_`a-z|~]+$/
```

> [!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`.

### 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.

```typescript
  const req = new Request(input, {
    ...buildRequestInitFromRequest(raw, strictConnectionProcessing),
    ...preprocessRequestInit(requestInit as RequestInit),
  })
  req.headers.delete('accept-encoding')

  const res = await (customFetch || fetch)(req)
```

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.

## Related

- [Application Core](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/core-engine/application-core)
- [Execution Context](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/core-engine/execution-context)
- [Middleware Composition](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/core-engine/middleware-composition)


## Sitemap

See the full [sitemap](https://www.doc0.dev/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/llms.txt) for all pages in this wiki.
