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());Report a problem with this exampleOpens a pre-filled issue on GitHub.