Orientation Arc
Routing Algorithms
Rendering and JSX
Runtime Adapters
Middleware Ecosystem
Developer Helpers
System Utilities
The following files were used as context for generating this wiki page:
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 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:
Content-Type against regex patterns (like jsonRegex or multipartRegex) to ensure compatibility with the requested target.c.req.json() or by processing the request buffer into FormData).validationFunc(value, c).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
The subsystem supports several predefined targets for data extraction, mapped internally to the structure of the incoming request:
multipart/form-data or x-www-form-urlencoded.Sources: src/validator/validator.ts:93-148
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, src/validator/validator.ts:89-148
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.
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
This example demonstrates using the validator to process JSON input and enforce validation rules before the handler executes.
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
Sources: src/validator/validator.ts:89-148