Overview
Hono provides a built-in validator middleware that lets you inspect and validate incoming request parameters, query values, headers, payloads, and cookies with end-to-end type safety. Validation works seamlessly with schema-driven validation libraries (such as Zod) so that your route handlers receive fully typed, trusted data.
Supported Validation Targets
The validator middleware supports six distinct parts of an incoming request.
| Target | Description | Content Type / Source |
|---|---|---|
json | JSON request payload | application/json |
form | Form data / multipart payloads | multipart/form-data, application/x-www-form-urlencoded |
query | Query string parameters | URL search parameters |
param | Route path parameters | URL path segments |
header | HTTP headers | Request headers |
cookie | Request cookies | Cookie header |
Note
GET and HEAD requests cannot carry a body content. Attempting to use body-based validation targets like json or form on GET or HEAD routes is restricted at compile time.
Step-by-Step Instructions
1. Import the validator helper
Import validator from the core validator package:
import { validator } from 'hono/validator'2. Apply the validator middleware to a route
Pass the validation target and a validation callback function to your route definition. The callback receives the raw value for that target and the context object c.
app.post(
'/posts',
validator('json', (value, c) => {
// Perform your validation checks here
if (!value || typeof value.title !== 'string') {
return c.text('Invalid title', 400)
}
return value
}),
(c) => {
const body = c.req.valid('json')
return c.json({ message: `Created post: ${body.title}` })
}
)3. Retrieve validated data in your handler
Inside your route handler, call c.req.valid(target) to access the sanitized, typed data returned by your validation function.
app.get(
'/search',
validator('query', (value, c) => {
return {
q: value.q || '',
limit: value.limit ? Number(value.limit) : 10,
}
}),
(c) => {
const { q, limit } = c.req.valid('query')
return c.json({ query: q, limit })
}
)Key Concepts
- Validation Function Signature: A validation function has the signature
(value, c) => OutputType | TypedResponse | Promise<OutputType> | Promise<TypedResponse>. If it returns aResponse(or aTypedResponse), Hono aborts the request chain immediately and returns that response to the client. - Automatic Parsing: For
jsontargets, Hono automatically parses the incoming request body as JSON and catches malformed payloads, throwing a400status error if parsing fails. Forformtargets, it parses URL-encoded or multipart form data into a structured record.
Tip
You can integrate third-party schema validation libraries (such as Zod) inside the validator callback by passing your schema's parse or safeParse result directly.
Warning
Do not attempt to use json or form validation targets on GET or HEAD requests. HTTP specifications disallow bodies on these methods, and Hono's type system will prevent it.