Skip to content

fix: support Zod-generated schemas with $schema property #6281

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mcollina
Copy link
Member

@mcollina mcollina commented Aug 8, 2025

Summary

  • Fixes Add Support for Zod Exported JSON Schema #6279 by adding support for JSON schemas containing the $schema meta-property
  • Allows Zod's toJSONSchema() output to work seamlessly with Fastify's validation system
  • Strips the $schema property from schemas before validation to prevent "no schema with key or ref" errors

Implementation Details

  • Added stripSchemaKeyword() helper function that safely removes $schema while preserving all other schema properties
  • Applied the fix to all validation paths: headers, body, querystring, and params schemas
  • Handles both simple schemas and content-type-specific schemas
  • No breaking changes - existing functionality is preserved

Test Coverage

  • Added comprehensive test covering all schema types (headers, body, querystring, params) with $schema property
  • Tests both valid and invalid request scenarios to ensure validation still works correctly
  • All existing tests continue to pass

Related Issues

Closes #6279

Fixes #6279 by stripping the $schema meta-property from schemas before
validation. This allows Zod's toJSONSchema() output to work seamlessly
with Fastify's validation system without throwing "no schema with key
or ref" errors.

The fix preserves all schema validation functionality while safely
ignoring the JSON Schema meta-schema declaration.
@mcollina mcollina requested a review from climba03003 August 8, 2025 16:20
@climba03003
Copy link
Member

It doesn't like a good idea to remove the $schema property.
It tells the validator whether it can support the schema and most recent schema is not backward compatible.

If the defined schema is draft-04, he or she should use the ajv@6 instead.
https://ajv.js.org/guide/schema-language.html#draft-04

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Support for Zod Exported JSON Schema
2 participants