Hono Zod Validator Middleware

Validate Hono route inputs with a Zod validator middleware that guards JSON bodies, returns field errors, and infers handler types.

TypescriptForm Validation

Code

typescriptsnippet
34 lines
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-validator and zod — 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

FAQ

Does this require external packages?
Yes — `hono`, `@hono/zod-validator` and `zod`. Add them to your project before running the snippet.