Skip to Content
hono-bento

Validation

Zod schemas validate the body, query and path params before your handler runs.

validation: {
  body: todoCreateSchema,
  query: listQuerySchema,
  params: z.object({ id: z.string().startsWith('todo_') }),
}

Prop

Type

Failures

  • A body that can't be parsed (invalid JSON, or malformed form data) gets 400 invalid_request.
  • A value that fails its schema gets 400 validation_error. The message names the part that failed (the request body, query string or path parameters), and each issue is listed:
{
  "error": {
    "type": "validation_error",
    "message": "The request body did not match the expected schema.",
    "errors": [{ "path": "title", "message": "Too small: expected string to have >=1 characters" }]
  },
  "status": 400
}

Handlers get the parsed values

The handler's body, query and params are the schemas' outputs, not the raw request, so coercions, defaults and transforms have already run:

export const todoListQuerySchema = z.object({
  limit: z.coerce.number().int().min(1).max(100).default(20),
});
// ?limit=5 → query.limit === 5 (a number); no limit → 20

A handler typed from its route's contract gets these types automatically.

Strict by default

Unknown body keys are rejected. That catches typos ({ "titel": "..." }) instead of silently ignoring them. Set strict: false on a route to allow extra keys.

Form data

Set contentType: 'form-data' to accept multipart/form-data (or application/x-www-form-urlencoded) instead of JSON. The form is parsed into a record of strings and Files, with repeated fields as arrays, and then validated by body like a JSON body, strict by default:

validation: {
  body: z.object({
    title: z.string().min(1),
    file: z.file().max(5_000_000).openapi({ type: 'string', format: 'binary' }),
  }),
  contentType: 'form-data',
}
// The handler's body is { title: string; file: File }.

The OpenAPI document lists the body as multipart/form-data. Give file fields .openapi({ type: 'string', format: 'binary' }): the OpenAPI generator can't describe z.file() on its own and throws without it.

Per-strategy bodies

validation: {
  body: projectUpdateSchema,
  bodyByStrategy: { apiKey: projectUpdateWithOwnerSchema },
}

The schema is picked by the name of the strategy that authenticated the request, so authentication always runs before validation. The handler's body type is the union of the schemas' outputs.

On this page