---
title: "Traffic Control"
description: "Traffic control in Hono is a layered responsibility distributed across its core router, middleware ecosystem, and platform-specific adapters. Fundamentally, it provides the mechanisms for routing r..."
last_updated: "2026-07-02T09:13:47.270018+00:00"
canonical_url: "https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/middleware-ecosystem/traffic-control"
---

<details>
<summary>Relevant source files</summary>

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

- [src/types.ts](https://github.com/blade47/hono/blob/main/src/types.ts)
- [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/main/src/adapter/aws-lambda/handler.ts)
- [src/context.ts](https://github.com/blade47/hono/blob/main/src/context.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/main/src/hono-base.ts)
- [src/middleware/ip-restriction/index.ts](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts)
</details>

Traffic control in Hono is a layered responsibility distributed across its core router, middleware ecosystem, and platform-specific adapters. Fundamentally, it provides the mechanisms for routing requests to the appropriate handlers and enforcing access policies based on request attributes, such as remote IP addresses. By decoupling path-based dispatching from security-oriented traffic filters, Hono ensures that traffic control remains performant and extensible.

The system acts as a pipeline: incoming requests are intercepted by platform adapters (like those in `src/adapter/aws-lambda/handler.ts`), processed through path matching in the core `Hono` class, and potentially validated by middleware such as `ip-restriction` before reaching their final handlers. This modular design prevents complex security logic from bloating the core router, allowing developers to apply granular control where needed.

Traffic control logic within Hono prioritizes speed and type safety, leveraging TypeScript to ensure route definitions and schema outputs are validated at compile time. Whether managing binary content encoding in serverless environments or enforcing subnet-level access, Hono's traffic control mechanisms offer a robust foundation for building secure and scalable network applications.

## Request Dispatching and Routing

The core of traffic control is the routing mechanism implemented in the `Hono` class defined in `src/hono-base.ts`. The router dispatches incoming requests by matching the request method and path against a pre-registered tree of handlers. The `Hono` class maintains a `routes` array and a router instance, ensuring that path resolution is consistent across different environments.

Routing is driven by the `fetch` method, which initiates the processing logic that triggers path extraction, router matching, and finally the execution of the handler pipeline. This sequence processes the request flow:

1. `fetch()` → `this.getPath()` (extracts path) → `this.router.match()` (finds handlers)
2. `new Context()` (instantiates context with match results)
3. `compose()` (runs middleware and handler pipeline)
4. `c.res` (returns the result, finalizes the context)

The router performs a lookup based on `request.method` and `path`. The match result contains an ordered array of handler sets. The `compose()` function is then responsible for iterating through these handlers, ensuring that any middleware in the chain can control the flow by calling or skipping `next()`.

Sources: [src/hono-base.ts:406-466](https://github.com/blade47/hono/blob/main/src/hono-base.ts#L406-L466), [src/hono-base.ts:479-485](https://github.com/blade47/hono/blob/main/src/hono-base.ts#L479-L485)

## IP Restriction Middleware Mechanism

The `ip-restriction` middleware provides granular control over which clients can interact with specific routes or the entire application. It works by evaluating the remote IP address of a request against defined `denyList` and `allowList` rules before the main handler is executed.

The mechanism relies on `buildMatcher`, which pre-compiles IP rules into an efficient validator. Static IPs, CIDR blocks, and custom functions are normalized into a single function that checks the remote IP's binary representation.

> [!TIP]
> Pre-compiling rules in `buildMatcher` avoids re-parsing CIDR strings on every request, significantly optimizing performance during high traffic.

When a request arrives, the `ipRestriction` middleware retrieves the client IP address using the function passed as the first argument (such as `getConnInfo`). The evaluation order is strictly defined:
1. **Deny List:** If the IP matches any rule in `denyList`, the request is immediately rejected with a 403 Forbidden (or a custom error).
2. **Allow List:** If the IP matches any rule in `allowList`, the request proceeds to the next middleware or handler.
3. **Implicit Deny:** If an `allowList` is provided but no rules match, the request is denied.

Sources: [src/middleware/ip-restriction/index.ts:51-167](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts#L51-L167), [src/middleware/ip-restriction/index.ts:218-278](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts#L218-L278)

## Adapter-Level Traffic Transformation

Adapters like `aws-lambda` serve as the entry point for cloud traffic. They translate platform-specific event objects (e.g., `APIGatewayProxyEvent`) into standardized `Request` objects that Hono understands.

The various processor classes (such as `EventV1Processor`, `ALBProcessor`, and `EventV2Processor`) handle the translation of platform-specific headers and query parameters into a uniform `Request` object. Crucially, they handle traffic encoding—if `isContentTypeBinary` is true, the adapter base64-encodes the response body before returning it to the AWS Lambda runtime.

| Processor Class | Target Environment |
| :--- | :--- |
| `EventV1Processor` | API Gateway Proxy Events (v1) |
| `EventV2Processor` | API Gateway Proxy Events (v2) |
| `ALBProcessor` | Application Load Balancer Events |
| `LatticeV2Processor` | VPC Lattice Events (v2) |

Sources: [src/adapter/aws-lambda/handler.ts:278-402](https://github.com/blade47/hono/blob/main/src/adapter/aws-lambda/handler.ts#L278-L402), [src/adapter/aws-lambda/handler.ts:639-651](https://github.com/blade47/hono/blob/main/src/adapter/aws-lambda/handler.ts#L639-L651)

## Architecture and Design Trade-offs

The Hono architecture favors modularity over monolithic control structures. By using `compose`, the framework treats handlers, middleware, and error handlers as a unified pipeline.

| Design Choice | Benefit | Cost |
| :--- | :--- | :--- |
| Middlewares as functions | Highly composable, testable | Requires explicit `await next()` |
| Pre-compiled Matchers | High-speed traffic filtering | Initial overhead at startup |
| Adapter Pattern | Supports multiple cloud platforms | High complexity in adapter logic |

Sources: [src/hono-base.ts:406-466](https://github.com/blade47/hono/blob/main/src/hono-base.ts#L406-L466), [src/middleware/ip-restriction/index.ts:51-167](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts#L51-L167)

## Traffic Control Lifecycle

The following diagram illustrates how a request flows through the traffic control stack:

```mermaid
flowchart TD
    A[Incoming Request] --> B{Adapter}
    B -->|Convert Event| C[Hono fetch]
    C --> D[Middleware Chain]
    D --> E{Router}
    E --> F[Target Handler]
    F --> G[Response Object]
    G --> B
    B --> H[Platform Result]
```

Sources: [src/hono-base.ts:479-485](https://github.com/blade47/hono/blob/main/src/hono-base.ts#L479-L485), [src/adapter/aws-lambda/handler.ts:252-276](https://github.com/blade47/hono/blob/main/src/adapter/aws-lambda/handler.ts#L252-L276)

## Implementation Example: IP Restriction

The following code demonstrates applying traffic control by restricting access to an `/admin` route using a custom IP list.

```typescript
import { Hono } from 'hono'
import { ipRestriction } from 'hono/ip-restriction'
import { getConnInfo } from 'hono/cloudflare-workers'

const app = new Hono()

// Apply IP restriction only to admin routes
app.use(
  '/admin/*',
  ipRestriction(getConnInfo, {
    allowList: ['203.0.113.0/24'], // Only allow this subnet
    denyList: ['203.0.113.5'],     // Specifically block one IP in that subnet
  })
)

app.get('/admin/dashboard', (c) => c.text('Welcome, Administrator'))
```

Sources: [src/middleware/ip-restriction/index.ts:188-216](https://github.com/blade47/hono/blob/main/src/middleware/ip-restriction/index.ts#L188-L216)

## Related

- [Security Headers](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/middleware-ecosystem/security-headers)


## Sitemap

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