Hono Zod Validator Middleware
Validate Hono route inputs with a Zod validator middleware that guards JSON bodies, returns field errors, and infers handler types.
Code
import { Hono } from 'hono';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';
// zValidator is the validation middleware mounted at route level
const app = new Hono();
const EventSchema = z.object({
title: z.string().min(3).max(120),
startsAt: z.string().datetime(),
capacity: z.number().int().min(1).max(10_000),
tags: z.array(z.string().min(1)).max(6).default([]),
});
app.post('/events', zValidator('json', EventSchema), (c) => {
const event = c.req.valid('json');
return c.json({
created: true,
title: event.title,
tags: event.tags,
startsAt: new Date(event.startsAt).toISOString(),
});
});
app.get('/events/:id', zValidator('param', z.object({ id: z.string().uuid() })),
(c) => c.json({ id: c.req.valid('param').id }));
const res = await app.request('/events', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ title: 'launch', startsAt: new Date().toISOString(), capacity: 50 }),
});
console.log('status:', res.status, await res.text());Inside the snippet
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The import line is the dependency contract: Hono, zValidator, z come from hono and nothing else.
Module-level bindings hold the data — app, EventSchema, res — with no function scope in between.
What to watch for
- Dependency check:
hono,@hono/zod-validatorandzod— not built-in, must be present in the project.
Using it
Running the file prints labeled results such as status: — each operation’s effect is visible in the output.
Key statements
app.post('/events', zValidator('json', EventSchema), (c) => {
const event = c.req.valid('json');
return c.json({
created: true,
title: event.title,
tags: event.tags,
startsAt: new Date(event.startsAt).toISOString(),
});
});
const res = await app.request('/events', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ title: 'launch', startsAt: new Date().toISOString(), capacity: 50 }),
});
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Does this require external packages?
- Yes — `hono`, `@hono/zod-validator` and `zod`. Add them to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.