Skip to main content
Sonamu uses Zod to validate TypeScript types at runtime. This document explains all features and patterns of Zod validation.

API HTTP validator optimization

Sonamu creates the final REST fastifyCaster validator once per handler lifetime. This cache is the default and needs no configuration. zod-compiler is an opt-in compilation step for that final validator.

Configuration

sonamu.config.ts
  • With no setting, or with zodCompiler: false, the API uses cached plain Zod.
  • jit suits a long-lived Node.js server. Sonamu compiles eagerly while preparing routes and fails server startup if compilation does not install the public parse methods.
  • aot compiles only the generated registry during pnpm sonamu build api. Source development uses cached plain Zod. Production startup verifies the registry fingerprint and route coverage.
  • Web and Expo compiler targets are unavailable and remain deferred.
  • validation.zodCompiler.targets is rejected; configure only validation.zodCompiler.api in this API-only phase.
Sonamu carries the runtime dependency used by JIT. Existing projects only need to add the validated compiler version to the API package before enabling AOT, because the generated source imports its build helper directly:

As-is and to-be

Known behavioral differences

In zod-compiler 1.23.6, records iterate enumerable string keys, some containers preserve the input reference, and per-call parse options are ignored. Schema-level errors and z.config() still apply. See the upstream Behavioral Differences section for details. Sonamu’s representative HTTP coercion and error paths passed parity checks, but applications that depend on container identity or symbol keys should verify those cases before opting in. To roll back, remove validation.zodCompiler or set it to false, remove the API package’s zod-compiler development dependency, then run sync and build again. Sync deletes the generated AOT registry. The handler cache and existing BadRequestException/ZodError contract remain in place. See docs/benchmarks/zod-compiler-http-validation.md in the repository for the measured setup and results. In the refreshed five-run benchmark, eager JIT and AOT reduced validator-only median p95 by 58.7% and 58.0%, respectively, but neither reached the 10% gate at the Fastify inject layer. The compiler modes therefore remain opt-in.

What is Zod?

Type-Safe Schema

Auto TypeScript type inference - No separate type definition needed

Runtime Validation

Actual data validation at execution - Block invalid data

Detailed Errors

Field-by-field error messages - Easy debugging

Transform & Defaults

Data transformation and defaults - Flexible handling

Basic Usage

Zod schemas are auto-generated from Entities, but you can also define them manually.

Schema Definition

Data Validation

parse vs safeParse:
  • parse(): Throws errors. Handle with try-catch
  • safeParse(): Returns errors. Check with result.success
Use parse() in API handlers to automatically return 400 errors, and use safeParse() in UI for safe handling.

Basic Type Validation

Zod validation for each Entity type.

String Validation

Number Validation

Date Validation

Boolean Validation

Complex Type Validation

Arrays

Objects

Enums

Union (one of multiple types)

Advanced Validation Patterns

Conditional Validation

Data Transformation

Default Values

Practical Validation Patterns

API Parameter Validation

What API Parameter Types Validate

The parameter types of an @api method are turned into a Zod validator that checks HTTP requests.
  • Named types inside an inline object, such as params: { data: UserSaveParams }, are validated with their Zod schemas. The same goes for arrays, Pick/Omit/Partial, and nested objects. With a plain z.object schema, undeclared keys are stripped and invalid values are rejected with 400.
  • null accepts only null, and true/false accept only that value. T | undefined accepts T or an omitted key, and void accepts only omission. For example, "asc" | "desc" | null accepts exactly those three values.
  • In GET query strings, "true"/"false" become booleans for boolean or a single true/false literal parameter, but not for a true | false union, so declare such a parameter as boolean.
  • Named types without a Zod schema, and any/unknown, are not validated, and neither are unions that contain them. Define the types you accept from requests as Zod schemas.

Business Logic Validation

Form Validation

Error Handling

ZodError Structure

Custom Error Messages

Error Formatting

Performance Optimization

Schema Reuse

Partial Validation

Next Steps

E2E Type Safety

End-to-end type safety

Entity Types

Entity type conversion

Generated Types

Using generated types

Model Testing

Testing Zod validation