#zod validator for schema

3 messages · Page 1 of 1 (latest)

cosmic jackal
#

Can I use zod validators and use them in the schema definitions?

ashen marshBOT
#

Hi @cosmic jackal. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

You can partially use Zod, but not directly as Convex schema validators.

Convex schemas must be defined with Convex’s own v validators (v.string(), v.object(), etc.). [Validators]

However, there is an official pattern (via convex-helpers) to convert Zod schemas into Convex validators:

  • For function arguments, you can define Zod schemas and then use helpers like zCustomQuery / zQuery which:

    1. Convert Zod → Convex validator with zodToConvex so Convex can validate and type your function.
    2. Run the Zod validation at runtime for stricter checks (e.g. z.string().email()). [Zod server args]
  • For database schemas, you can use zodOutputToConvex to turn a Zod schema into a Convex validator and then pass that into defineTable. This works, but the docs explicitly warn that:

    • Convex only enforces the v-level type (e.g. v.string()), not the extra Zod refinements like .email() or .min(8).
    • So the stored data is guaranteed to match the Convex validator, but not necessarily all your Zod constraints, unless you also validate with Zod before writes / on reads. [DB via Zod]

So:

  • Yes: you can define Zod schemas and convert them into Convex validators for both function args and tables using convex-helpers.
  • But: Convex still needs its own v validators under the hood, and Zod’s extra constraints are only enforced where you explicitly run the Zod validation.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: