zod icon indicating copy to clipboard operation
zod copied to clipboard

`.meta()` is ignored in `toJSONSchema` unless its the last chained method (using Zod v4)

Open IdoBouskila opened this issue 1 month ago • 4 comments

Hi, when generating JSON Schema with z.toJSONSchema, metadata added with .meta() is only included if .meta() is the final method in the chain.

Example where metadata is lost:

const schema = z.object({
  name: z.string().meta({ describe: 'first name' }).min(1)
});

Example where metadata works:

```ts
const schema = z.object({
  name: z.string().min(1).meta({ describe: 'A user name' })
});

Is it expected? feels unintuitive that order matters here

Thanks for taking a look! 🙏

IdoBouskila avatar Nov 14 '25 11:11 IdoBouskila

Hi @IdoBouskila! I'm Dosu and I’m helping the zod team.

This is expected and intentional in Zod v4. Metadata added with .meta() (or .describe()) is attached to a specific schema instance, and most schema methods like .min(), .optional(), .extend(), etc. return a new schema instance that does not inherit metadata from the previous one. That's why metadata is only included in the JSON Schema output if .meta() is the last method in the chain—otherwise, it's lost on the new instance. This design reflects Zod's immutability and instance-based metadata association (docs, issue #5231, discussion 5037).

Best practice: always call .meta() (or .describe()) last, after all other transformations, to ensure metadata is retained in the JSON Schema output. If you need to add metadata after chaining, just reapply .meta():

const schema = z.object({
  name: z.string().min(1).meta({ describe: 'first name' })
});

For complex cases, you can manage metadata externally or reapply .meta() after each transformation. Let me know if you want a code helper for this. If this answers your question, please close the issue!

To reply, just mention @dosu.


How did I do? Good | Irrelevant | Incorrect | Verbose | Hallucination | Report 🐛 | Other  Chat with Dosu Join Discord Share on X

dosubot[bot] avatar Nov 14 '25 11:11 dosubot[bot]

I don't see that behavior documented anywhere, just referred to in the linked issues / discussions with responses from other AI bots. I think it would be great if meta data would be carried until it's overwritten in schema chains, it's the behavior I would expect

gr2m avatar Nov 14 '25 17:11 gr2m

@colinhacks can you let us know if changing the current behavior is both possible and desired? I'm sure we can put together a PR. ai SDK users repeatedly are confused by the current behavior.

gr2m avatar Nov 15 '25 22:11 gr2m

feels unintuitive that order matters here

It becomes intuitive after understanding that each refinement creates a new instance, @IdoBouskila

I don't see that behavior documented anywhere

https://zod.dev/metadata , @gr2m

Image

RobinTail avatar Nov 23 '25 07:11 RobinTail