Skip to content

← Blog#typescript

Zod as a Contract, Not a Comment

One Zod schema is your TypeScript type and your runtime validator. How I use Zod as the contract for forms, APIs and LLM output - and the bugs it deletes.

Muhammad Zain Ul Abidin5 min readUpdated November 10, 2026
On this page
Zod as a Contract, Not a Comment

When a TypeScript type meets untrusted JSON - from a form, a third-party API, an LLM response - the type is a comment. The runtime knows nothing about it. The type checker can't reach past the network. So we end up with two definitions for the same shape: the type, and a hand-rolled validator. They drift. Bugs follow.

Zod fixes this by making one definition produce both.

The pattern

The schema is the type. The schema is the validator. There is no second source.

ts
import { z } from "zod";

export const caseStudyFrontmatter = z.object({
  title: z.string().min(3),
  slug: z.string().regex(/^[a-z0-9-]+$/, "kebab-case"),
  oneLine: z.string().min(10).max(200),
  role: z.string(),
  stack: z.array(z.string()).min(1),
  liveUrl: z.string().url().optional(),
  order: z.number().int().nonnegative(),
});

export type CaseStudyFrontmatter = z.infer<typeof caseStudyFrontmatter>;

The static type comes from z.infer. The runtime validator comes from .parse(). They cannot drift, because they are the same thing.

Where this earns its keep

Three places. All three are zones where untrusted JSON meets your types.

1. LLM output

You ask Gemini to return JSON. Gemini complies - sometimes. Sometimes it returns prose. Sometimes it returns JSON with one field misnamed. A schema catches all of these and lets you retry with a corrective system message before the bad data touches your domain logic. I run this in production in ComplianceBot AI, where every AI-generated document section is validated against its own Zod schema before it is assembled.

2. Form payloads

A <form> is hostile input by default. Zod runs the same check on the server that ran on the client, so a malicious actor sending a hand-crafted POST gets the same rejection a real user gets - without a second hand-rolled validator.

3. Build-time content

MDX frontmatter is just YAML. YAML is not typed. A schema turns it into a typed value at build time, with line-and-column errors when a post is malformed.

A small but real example

Suppose your blog accepts cross-posts. Some posts are originals; some are republished from dev.to with a canonical pointing back. The schema describes both states clearly:

ts
const post = z.object({
  title: z.string().min(3),
  externalCanonical: z.string().url().optional(),
  syndicatedTo: z.array(
    z.object({
      platform: z.enum(["devto", "medium", "hashnode"]),
      url: z.string().url(),
    })
  ).optional(),
});

If externalCanonical is set, your sitemap excludes the post (SEO weight goes elsewhere). If syndicatedTo is set, your post page renders an "Also published on" footer. These behaviors aren't documented in a comment - they're enforced by the schema and consumed by typed code.

zod.dev

Zod - the docs

Comprehensive reference for the schema-as-validator-as-type pattern.

Validate at the boundary, then trust the type

The rule I follow: parse once, at the edge where data enters the system, and never again inside. A request body, a webhook payload, a row from a queue, a model response - each gets parsed the moment it arrives. After that line, the rest of the code works with a typed value and does not re-check it.

ts
const createInvoice = z.object({
  customerId: z.string().uuid(),
  amountCents: z.number().int().positive(),
  currency: z.enum(["USD", "EUR", "GBP"]),
  note: z.string().max(500).optional(),
});

type CreateInvoice = z.infer<typeof createInvoice>;

export async function handleCreate(raw: unknown) {
  const input = createInvoice.parse(raw); // the only check
  return invoices.create(input); // typed from here on
}

Notice the parameter is unknown, not CreateInvoice. That is deliberate. If the function claims to accept a typed value, every caller can skip the parse and the boundary quietly disappears. Taking unknown forces the check to happen where it belongs.

parse vs safeParse

Zod gives you two ways to run a schema, and the choice is about control flow.

.parse() returns the typed value or throws a ZodError. I use it where a failure is a bug or a broken deploy: build-time content, environment variables, config files. There is nothing sensible to do except stop.

.safeParse() never throws. It returns a result you branch on. I use it where failure is expected and has to be handled: user input, third-party responses, LLM output.

ts
const result = createInvoice.safeParse(body);

if (!result.success) {
  return Response.json(
    {
      error: "invalid_request",
      issues: result.error.issues.map((i) => ({
        path: i.path.join("."),
        message: i.message,
      })),
    },
    { status: 400 },
  );
}

const invoice = await invoices.create(result.data);

Throwing for a bad form field means using exceptions as control flow, and it pushes the error mapping into whatever catches it. safeParse keeps the decision next to the code that knows what a 400 should look like.

Mapping errors to a useful response

Every Zod issue carries a path (where in the input it failed), a message and a code. That is enough to build an error shape your client can act on. I return a flat list of { path, message } pairs: the form reads it and puts each message next to the right field, and the API consumer reads it and knows exactly which property to fix.

Two things I keep out of that response. First, the raw input: echoing it back is a good way to leak whatever someone pasted into a field. Second, stack traces or internal names. The client needs to know what was wrong with its request, not how my code is laid out.

One schema, both sides of the wire

The real payoff shows up when the client and the server import the same schema from a shared package. In a monorepo I put schemas in their own package with no runtime dependencies besides Zod, so both the frontend and the backend can import it without dragging anything else along.

On a NestJS backend, a small pipe runs the schema on the incoming body:

ts
import { BadRequestException, PipeTransform } from "@nestjs/common";
import type { ZodType } from "zod";

export class ZodPipe<T> implements PipeTransform<unknown, T> {
  constructor(private readonly schema: ZodType<T>) {}

  transform(value: unknown): T {
    const result = this.schema.safeParse(value);
    if (!result.success) {
      throw new BadRequestException(
        result.error.issues.map((i) => ({ path: i.path.join("."), message: i.message })),
      );
    }
    return result.data;
  }
}

// In the controller:
// @Post() create(@Body(new ZodPipe(createInvoice)) body: CreateInvoice) { ... }

In a Next.js route handler it is the safeParse block from above. On the client, the same schema validates the form before submit, so the user sees the error without a round trip. The check the client runs and the check the server enforces are one object. When I add a field, both sides change in the same commit, and the compiler shows me every place that has to handle it.

Common mistakes

Casting instead of parsing. JSON.parse(text) as User compiles and proves nothing. It is the exact drift this pattern exists to remove. If the data came from outside the process, it goes through a schema.

Using z.infer when you mean the input. Schemas with .default() or .transform() have a different shape before and after parsing. z.infer (the same as z.output) is the parsed shape. For a form's initial values or a function that accepts the raw payload, use z.input instead.

Strict schemas on data you don't own. By default an object schema strips unknown keys, which is what you want for a third-party API: they add a field, nothing breaks. .strict() rejects unknown keys. I use it on my own endpoints, where an unexpected key usually means a client bug, and never on responses I don't control.

Forgetting that query strings are strings. ?page=2 arrives as "2". z.number() rejects it. z.coerce.number() converts first, then checks.

Validating on the client only. Client validation is a courtesy to the user. The server check is the contract. Anyone can send a request without your form.

When not to reach for it

Not every function needs a schema. Calls between modules inside one TypeScript program are already checked by the compiler, and re-parsing there adds cost and noise without catching anything. I also keep schemas out of hot loops that process data already validated upstream. Parsing is cheap, but it is not free, and running it on every iteration of a tight loop is paying twice for the same guarantee.

The line is simple: if the data crossed a boundary the type checker can't see - the network, the disk, a model, a user - parse it. If it didn't, trust the types.

The takeaway

Treat schemas as contracts, not comments. Make the type and the validator the same artifact. Let the build break loudly when content is malformed. You'll remove a category of bug - drift between what your types claim and what your runtime accepts - that no amount of testing will fully cover.

The same drift question runs through the data layer, which is why I compared Prisma 8 vs Drizzle: both tools start from a schema, and their disagreement about where that schema lives decides how much drift you police yourself.

Try it on your own data: JSON to Zod turns a sample or a JSON Schema into a Zod schema, and the Tool Schema Validator checks a tool definition before a model ever sees it.

Also published on

Comments

No comments yet. Be the first.

Leave a comment

Comments are reviewed before they appear.