---
title: "Schema Validation"
description: "Schema Validation is a core mechanism in Hono that enables declarative runtime verification of incoming request data. By coupling request targets (e.g., `json`, `query`, `param`) with user-defined ..."
last_updated: "2026-07-02T09:13:47.28271+00:00"
canonical_url: "https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/developer-helpers/schema-validation"
---

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

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

- [src/adapter/aws-lambda/handler.ts](https://github.com/blade47/hono/blob/main/src/adapter/aws-lambda/handler.ts)
- [src/types.ts](https://github.com/blade47/hono/blob/main/src/types.ts)
- [src/middleware/secure-headers/secure-headers.ts](https://github.com/blade47/hono/blob/main/src/middleware/secure-headers/secure-headers.ts)
- [src/request.ts](https://github.com/blade47/hono/blob/main/src/request.ts)
- [src/hono-base.ts](https://github.com/blade47/hono/blob/main/src/hono-base.ts)
- [src/validator/validator.ts](https://github.com/blade47/hono/blob/main/src/validator/validator.ts)
</details>

Schema Validation is a core mechanism in Hono that enables declarative runtime verification of incoming request data. By coupling request targets (e.g., `json`, `query`, `param`) with user-defined validation functions, Hono ensures that downstream handlers receive processed and verified data. This architecture shifts the responsibility of data integrity from the business logic layer into a composable pipe, reducing boilerplate error handling code within routes.

The design centers on the `validator` function, which integrates with Hono’s request lifecycle. When a request hits a registered endpoint, the validator inspects the request, extracts data segments based on a specified target, and passes them to a validation function. If validation fails or the request payload is malformed, the validator terminates the request chain. Successful validation results are then attached to the `HonoRequest` instance, allowing handlers to access them via `c.req.valid()`.

This subsystem is tied to Hono’s type-safety system. By defining custom types for `Input`, developers can propagate validation outcomes through the application stack. This creates a contract-first development flow where the validation logic at the edge of the system dictates the signatures of request objects within the handler, ensuring robust data handling alongside validation.

## The Validator Mechanism

The `validator` function is a higher-order function that returns an asynchronous request handler. Its primary mechanism involves detecting the incoming request's `Content-Type`, extracting the requested data segment, and executing the provided validation function.

When `validator(target, validationFunc)` is invoked:
1. It returns an async function that intercepts the request processing chain.
2. Inside, it checks the `Content-Type` against regex patterns (like `jsonRegex` or `multipartRegex`) to ensure compatibility with the requested target.
3. If the type matches, it parses the body (e.g., using `c.req.json()` or by processing the request buffer into `FormData`).
4. The parsed value is passed to `validationFunc(value, c)`.
5. If the result from `validationFunc` is a `Response`, the validator short-circuits the pipeline. Otherwise, it invokes `c.req.addValidatedData(target, data)` to store the result.

Sources: [src/validator/validator.ts:46-150](https://github.com/blade47/hono/blob/main/src/validator/validator.ts#L46-L150)

## Supported Data Targets

The subsystem supports several predefined targets for data extraction, mapped internally to the structure of the incoming request:

*   **json**: Parses the request body as JSON.
*   **form**: Parses `multipart/form-data` or `x-www-form-urlencoded`.
*   **query**: Extracts data from URL query parameters.
*   **param**: Extracts path parameters from the routing context.
*   **header**: Extracts request headers.
*   **cookie**: Extracts browser cookies.

Sources: [src/validator/validator.ts:93-148](https://github.com/blade47/hono/blob/main/src/validator/validator.ts#L93-L148)

## Lifecycle Integration

Validation is a crucial step in the Hono request pipeline. By attaching data to the `HonoRequest` instance using `addValidatedData`, the system guarantees that when a handler eventually executes, it does not need to perform redundant parsing or type validation.

> [!TIP]
> Place the `validator` early in the execution chain to ensure that subsequent handlers receive clean, validated data and to prevent unnecessary processing if the input is malformed.

Sources: [src/request.ts:334-341](https://github.com/blade47/hono/blob/main/src/request.ts#L334-L341), [src/validator/validator.ts:89-148](https://github.com/blade47/hono/blob/main/src/validator/validator.ts#L89-L148)

## Error Handling and Invariants

The `validator` ensures strict adherence to the expected format. If a request claims to be `application/json` but contains invalid syntax, the validator catches the failure and throws an `HTTPException`.

```typescript
try {
  value = await c.req.json()
} catch {
  const message = 'Malformed JSON in request body'
  throw new HTTPException(400, { message })
}
```

This guard line is load-bearing; it ensures that the `validationFunc` is never invoked with unparseable data, maintaining the invariant that the input to the user's validation logic is always syntactically correct.

Sources: [src/validator/validator.ts:98-103](https://github.com/blade47/hono/blob/main/src/validator/validator.ts#L98-L103)

## Worked Example

This example demonstrates using the validator to process JSON input and enforce validation rules before the handler executes.

```typescript
import { Hono } from 'hono'
import { validator } from 'hono/validator'

const app = new Hono()

app.post(
  '/user',
  validator('json', (value, c) => {
    if (typeof value.name !== 'string') {
      return c.text('Invalid name', 400)
    }
    return value
  }),
  (c) => {
    const data = c.req.valid('json')
    return c.json({ message: `Hello ${data.name}` })
  }
)
```

Sources: [src/validator/validator.ts:46-88](https://github.com/blade47/hono/blob/main/src/validator/validator.ts#L46-L88)

## Design Trade-offs

| Design Choice | Benefit | Cost |
| :--- | :--- | :--- |
| Pipeline-based validation | Decouples validation from route logic. | Introduces middleware overhead per request. |
| Functional injection | Highly flexible; custom logic allowed. | Increased developer burden for manual checks. |
| In-place data storage | Memory efficient; no extra objects created. | Modifies request state; requires careful lifecycle management. |

Sources: [src/validator/validator.ts:89-148](https://github.com/blade47/hono/blob/main/src/validator/validator.ts#L89-L148)

## Related

- [RPC Client](https://www.doc0.app/docs/552ca36e-f67e-41c3-a07a-def9bd9551b0/technical/developer-helpers/rpc-client)


## Sitemap

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