Skip to content

Zod Validator Overview

The @yelix/zod-validator package provides request validation middleware that integrates seamlessly with Yelix and automatically generates OpenAPI schemas from your Zod validation rules.

  • Type-Safe Validation: Validate requests using Zod schemas with full TypeScript support
  • Multiple Data Sources: Validate data from JSON body, query parameters, path parameters, headers, cookies, and form data
  • Automatic OpenAPI Generation: Automatically converts Zod schemas to OpenAPI schemas for documentation
  • Seamless Integration: Works perfectly with Yelix’s OpenAPI documentation system
  • Error Handling: Built-in error handling for validation failures
Terminal window
deno add jsr:@yelix/zod-validator npm:zod
import { YelixHono } from '@yelix/hono';
import { zValidatorYelix } from '@yelix/zod-validator';
import { z } from 'zod';
const app = new YelixHono();
app.post(
'/users',
zValidatorYelix('json', z.object({
name: z.string().min(1),
email: z.email(),
age: z.number().int().positive(),
})),
(c) => {
const data = c.req.valid('json' as never);
return c.json({ message: 'User created', data });
}
);

zValidatorYelix supports validating data from different sources:

  • json - Request body as JSON
  • form - Form data (multipart/form-data or application/x-www-form-urlencoded)
  • query - URL query parameters
  • param - URL path parameters
  • header - HTTP headers
  • cookie - HTTP cookies

You can use zValidatorYelix multiple times on the same route to validate different parts of the request (for example, headers and JSON body). Each middleware validates its source independently and you can access each result with c.req.valid.

import { YelixHono } from '@yelix/hono';
import { zValidatorYelix } from '@yelix/zod-validator';
import { z } from 'zod';
const app = new YelixHono();
app.post(
'/secure/users',
zValidatorYelix('header', z.object({
authorization: z.string().regex(/^Bearer\s.+$/),
})),
zValidatorYelix('json', z.object({
name: z.string().min(1),
email: z.email(),
})),
(c) => {
const headers = c.req.valid('header' as never);
const body = c.req.valid('json' as never);
return c.json({ message: 'User created', headers, body });
}
);