Zod OpenAPI
Zod-OpenAPI Integration Issues
We attempted to integrate Zod with OpenAPI using the zod-openapi library to automatically generate OpenAPI documentation while maintaining type-safe runtime validation. The integration aimed to streamline the development process by using Zod for both validation and documentation generation.
Challenges Encountered
- Issue with
$refandrequiredFields:- When using Zod schemas, the generated JSON schema often contained
$refreferences to thedefinitionsobject, which Fastify could not resolve, resulting in errors such as:-
can't resolve reference #/definitions/UserSchema. -
data/required must be array— Fastify requiresrequiredto be an array of field names (e.g.,['id', 'name', 'email']), butzod-openapididn’t automatically format therequiredfield as an array. -
here is the screenshot of the error:

-
- When using Zod schemas, the generated JSON schema often contained
- JSON Schema Generation:
- The Zod-to-JSON Schema conversion using
zod-openapiwas producing an incorrect schema format that Fastify couldn’t interpret. Specifically, thepropertiesfield was not properly set, and$refwas incorrectly being used in the schema, which Fastify doesn’t support.
- The Zod-to-JSON Schema conversion using
Converting this zod schema object by using zodToJsonSchema(UserSchema, 'UserSchema');
will result to:
- OpenAPI Documentation Integration:
- While
zod-openapigenerated the OpenAPI documentation correctly in most cases, Fastify’s Swagger plugin required the schema to be in a specific format, causing issues when trying to directly integrate Zod schemas into Fastify’s schema validation system.
- While
##Sample proof-of-concept Code
zod-openapi is not specifically designed for Fastify, it is primarily intended for OpenAPI documentation generation from Zod schemas.