Writeup · Nov 18, 2026 · 11 min read

Zod v3 Patterns: Schema Reuse, Refinements & tRPC Integration

Writeup

Practical Zod techniques for schema composition, async business rules, custom error mapping, Express middleware, tRPC procedures and React Hook Form. Includes complete code examples and explicit trade

Zod v3 Patterns: Schema Reuse, Refinements & tRPC Integration

Zod's Core Parsing Methods and When to Use Each

z.parse() and z.safeParse() behave differently in production code. parse() throws a ZodError immediately, making it the right choice inside tRPC procedures or server actions where you want the framework's error handling to catch and format the response. safeParse() returns {success: boolean, data?: any, error?: ZodError} and is required in middleware or edge functions where throwing would crash the request handler.

Version 3.23.8 of Zod (current as of late 2024) improved the performance of safeParse() by reducing object allocations during issue collection. For a 2 KB payload with 15 fields, the difference is sub-millisecond on Node 22, but the real value appears when you chain multiple refinements.

import { z } from "zod";

const LoginSchema = z.object({
  email: z.string().email("Invalid email format"),
  password: z.string().min(12, "Password must be at least 12 characters"),
});

const result = LoginSchema.safeParse(req.body);
if (!result.success) {
  return res.status(400).json({
    errors: result.error.issues.map(issue => ({
      path: issue.path.join("."),
      message: issue.message,
    })),
  });
}

The explicit mapping of issues to a flat array is a pattern used in most production codebases because frontend forms expect a consistent shape rather than the nested error.issues tree.

Building Reusable Schema Libraries Across Services

Instead of repeating z.string().uuid() or email regex patterns in every service, create a central @company/schemas package. This guarantees identical validation rules run in your Next.js API routes, your Python workers that consume the same events, and your mobile clients.

A typical reusable schema file looks like this:

import { z } from "zod";

export const EntityId = z.string().uuid();

export const Email = z
  .string()
  .email()
  .transform(val => val.toLowerCase().trim());

export const Password = z
  .string()
  .min(12)
  .regex(/[A-Z]/, "Must contain uppercase")
  .regex(/[a-z]/, "Must contain lowercase")
  .regex(/[0-9]/, "Must contain number");

export const UserProfileSchema = z.object({
  id: EntityId,
  email: Email,
  name: z.string().min(2).max(80),
  createdAt: z.date(),
});

export type UserProfile = z.infer<typeof UserProfileSchema>; 

z.infer gives you a TypeScript type that stays in sync with the runtime schema. When you add a new optional field to UserProfileSchema, both your backend controller and your frontend form types update automatically. This eliminates an entire class of "type drift" bugs that appear when teams maintain separate TypeScript interfaces and validation logic.

Trade-off: the central package increases compile times slightly in monorepos (roughly 400 ms extra on a 120-package Turborepo). The safety gain outweighs this cost once you have more than three services consuming the same data contracts.

Refinements for Business Rules That Cannot Be Expressed With Primitive Validators

.refine() lets you run arbitrary predicates. The most common production pattern combines synchronous checks with custom error paths.

const OrderSchema = z.object({
  items: z.array(
    z.object({
      productId: z.string().uuid(),
      quantity: z.number().int().positive(),
    })
  ),
  total: z.number().positive(),
}).refine(data => {
  const calculated = data.items.reduce((sum, item) => {
    // lookup price from cached catalog - omitted for brevity
    return sum + (item.quantity * 9.99);
  }, 0);
  return Math.abs(calculated - data.total) < 0.01;
}, {
  message: "Total does not match item prices",
  path: ["total"],
});

Placing the path on ["total"] means the frontend receives the error exactly where the designer expects it. Without the path option, the error would attach to the root object and UI code becomes messy.

For password confirmation you can use a two-step refinement on an object that contains both fields:

const RegistrationSchema = z
  .object({
    password: Password,
    confirmPassword: z.string(),
  })
  .refine(data => data.password === data.confirmPassword, {
    message: "Passwords do not match",
    path: ["confirmPassword"],
  });

Async Refinements for Database and External Service Checks

Many teams avoid async refinements because they fear they slow down the happy path. In practice, running a uniqueness check for an email address inside the validation layer is cleaner than doing it in the controller after parsing.

const CreateUserSchema = z.object({
  email: Email,
  name: z.string().min(2),
}).refine(async (data) => {
  const existing = await db.user.findUnique({
    where: { email: data.email },
  });
  return !existing;
}, {
  message: "Email already registered",
  path: ["email"],
});

const result = await CreateUserSchema.safeParseAsync(req.body);

safeParseAsync is the async counterpart. The performance cost is one extra database round-trip only on validation failure paths in most implementations, because you can short-circuit with a cached Bloom filter or Redis existence check before hitting Postgres. The pattern keeps controllers thin and moves all data rules into one place that can be unit-tested independently.

Error Mapping Strategies for Different Consumers

A single schema often serves both an API and a React form. The error shapes required differ. The .transform() method on the error object itself is not directly available, so the standard pattern is a dedicated mapper function.

function toFormErrors(zodError: z.ZodError) {
  return zodError.issues.reduce((acc, issue) => {
    const key = issue.path.join(".");
    acc[key] = issue.message;
    return acc;
  }, {} as Record<string, string>);
}

// In a Next.js server action
const result = Schema.safeParse(data);
if (!result.success) {
  return { 
    success: false, 
    fieldErrors: toFormErrors(result.error) 
  };
}

This mapper can be extended to return localized messages by looking up keys in a translation table. Keeping the mapping outside the schema keeps the schema itself portable to backend-only services that do not need i18n.

Discriminated Unions for API Versioning and Polymorphic Payloads

When your API accepts different event types on the same endpoint, discriminated unions give both runtime safety and exhaustive TypeScript checks.

const EventSchema = z.discriminatedUnion("type", [
  z.object({
    type: z.literal("user.created"),
    userId: z.string().uuid(),
    email: Email,
    timestamp: z.string().datetime(),
  }),
  z.object({
    type: z.literal("order.paid"),
    orderId: z.string().uuid(),
    amount: z.number().positive(),
    paymentMethod: z.enum(["card", "paypal", "bank"]),
  }),
]);

// TypeScript knows the exact shape inside each case
function handleEvent(event: z.infer<typeof EventSchema>) {
  if (event.type === "user.created") {
    // event.email is available with full type narrowing
    sendWelcomeEmail(event.email);
  }
}

This pattern appears in webhook handlers and queue consumers. Adding a new event type forces you to update the union, giving compile-time proof that every consumer has been reviewed.

Express Middleware That Reuses the Same Schemas as tRPC

Teams that maintain both REST endpoints and tRPC often duplicate validation. The following middleware pattern removes duplication.

import { Request, Response, NextFunction } from "express";

function validate(schema: z.ZodSchema) {
  return (req: Request, res: Response, next: NextFunction) => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      res.status(400).json({
        success: false,
        errors: result.error.issues,
      });
      return;
    }
    req.validatedBody = result.data; // typed with declaration merging
    next();
  };
}

// Usage
app.post(
  "/users",
  validate(CreateUserSchema),
  async (req, res) => {
    const data = req.validatedBody; // fully typed
    const user = await createUser(data);
    res.json(user);
  }
);

You extend Express.Request with a module declaration so req.validatedBody carries the exact inferred type from the schema passed to the middleware. The same CreateUserSchema can be used inside a tRPC input() without modification.

tRPC Integration and Automatic Type Generation

tRPC v11 natively accepts Zod schemas in the input() method. The framework extracts both the runtime validator and the TypeScript type.

export const appRouter = router({
  createUser: protectedProcedure
    .input(CreateUserSchema)
    .mutation(async ({ input, ctx }) => {
      // input is typed as z.infer<typeof CreateUserSchema>
      return db.user.create({ data: input });
    }),

  listUsers: publicProcedure
    .input(z.object({
      limit: z.number().int().min(1).max(100).default(50),
      cursor: z.string().uuid().optional(),
    }))
    .query(async ({ input }) => {
      // pagination logic
    }),
});

Because the input schema lives next to the procedure, frontend code generated by @trpc/client automatically receives the correct validation rules translated into TanStack Query types. Changing a field length constraint immediately updates both backend enforcement and frontend form validation without manual synchronization.

Trade-off: tRPC procedures become tightly coupled to the validation library. If you ever need to support a non-Zod consumer (for example a mobile team using Kotlin), you must maintain a separate OpenAPI spec or manual documentation. Most teams accept this because the productivity gain inside the TypeScript ecosystem is substantial.

Zod With React Hook Form and Server Actions

The zodResolver from @hookform/resolvers bridges the two libraries. A complete Next.js 15 server action example looks like this:

"use server";

import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";

const ProfileSchema = z.object({
  name: z.string().min(3).max(60),
  bio: z.string().max(500).optional(),
  website: z.string().url().optional().or(z.literal("")),
});

export async function updateProfile(prevState: any, formData: FormData) {
  const data = Object.fromEntries(formData);
  const validated = ProfileSchema.safeParse(data);
  
  if (!validated.success) {
    return {
      success: false,
      errors: validated.error.flatten().fieldErrors,
    };
  }

  await db.profile.update({
    where: { userId: ctx.user.id },
    data: validated.data,
  });

  return { success: true };
}

On the client you pass the same schema to useForm:

const form = useForm<z.infer<typeof ProfileSchema>>({
  resolver: zodResolver(ProfileSchema),
  defaultValues: { name: "", bio: "" },
});

The flatten() method on the error produces the exact shape React Hook Form expects for setError and field-level error display. This removes another layer of mapping code that would otherwise live in every form.

Performance Characteristics and Optimization Techniques

Zod 3.23 parses typical request payloads (under 5 KB) in 0.2–0.6 ms on a 2023 MacBook M2. The cost grows linearly with the number of refinements. Each .refine() adds a function call; each regex adds more. For high-throughput endpoints processing 2000 requests per second, move expensive checks (regex with backtracking risk or network calls) into a post-parse transform that runs only after basic shape validation succeeds.

Bundle size for a tree-shaken schema that uses 12 different validators is approximately 14 kB minified and gzipped. This is larger than Valibot (≈ 2.5 kB for equivalent schemas) but smaller than Yup. The difference becomes relevant only for edge-run functions where every kilobyte affects cold-start latency.

Optimization pattern used in production:

// Fast path schema used in hot route
const FastLoginSchema = z.object({
  email: Email,
  password: z.string().min(8), // minimal checks
});

// Full schema used only after rate-limit and basic auth pass
const FullLoginSchema = FastLoginSchema.extend({
  password: Password, // heavy regexes
}).refine(/* async checks */);

This two-stage validation keeps median latency low while still enforcing strict rules on requests that pass the initial gate.

Testing Schemas Independently With Vitest

Unit testing validation rules catches regressions when business logic changes. A typical test suite for a complex schema includes both valid and invalid cases with exact error path assertions.

import { describe, it, expect } from "vitest";
import { CreateUserSchema } from "./schemas";

describe("CreateUserSchema", () => {
  it("accepts valid payload", () => {
    const result = CreateUserSchema.safeParse({
      email: "test@example.com",
      name: "Valid User",
      password: "CorrectHorseBattery12",
    });
    expect(result.success).toBe(true);
  });

  it("rejects duplicate email with correct path", async () => {
    const result = await CreateUserSchema.safeParseAsync({
      email: "existing@example.com",
      name: "Test",
      password: "CorrectHorseBattery12",
    });
    expect(result.success).toBe(false);
    expect(result.error?.issues[0].path).toEqual(["email"]);
    expect(result.error?.issues[0].message).toContain("already registered");
  });
});

Because schemas are plain functions, they can be tested in isolation without spinning up a server or database (mock the async refine if needed). This practice keeps validation logic trustworthy over years of refactoring.

Common Pitfalls and Concrete Mitigations

One frequent mistake is using .default() with values that should be set by the server. A client can send an explicit value that bypasses the default. Prefer .optional().transform(val => val ?? serverDefault) or set defaults in the controller after successful parsing.

Another pitfall is overly strict string schemas that reject valid international names or addresses. Using z.string().min(1).max(120) without regex for most text fields is usually safer than trying to codify every cultural naming rule.

Overusing .transform() for business logic instead of keeping transformations inside service layers makes schemas harder to reason about. Reserve .transform() for normalization (trimming, lowercasing, date parsing) and leave domain operations to dedicated functions that receive already-validated data.

Finally, never use z.any() or z.unknown() as escape hatches in production schemas. Every schema that reaches the public internet should describe its expected shape completely. The few truly dynamic cases (webhook metadata from third parties) should use z.record(z.string(), z.any()) with explicit documentation that the values will be further sanitized downstream.

Comparing Zod With Valibot and Effect Schema for New Projects

Valibot offers smaller bundle sizes (often 70 % reduction) and better tree-shaking because each validator is individually importable. However, its API is less mature for complex async refinements and the error messages require more manual formatting. Teams already invested in tRPC usually stay with Zod because the integration is seamless and the ecosystem (documentation, Stack Overflow answers, blog posts) remains richer.

Effect Schema (formerly Schema from Effect-TS) provides compositional effects and better support for decoding from multiple formats (JSON, FormData, URLSearchParams). It is a strong choice for functional programmers who already use the Effect library for dependency injection and error handling. For most full-stack TypeScript teams that value simplicity and wide community support, Zod remains the default in 2025.

The decision matrix used by several consultancies is:

  • Need smallest possible bundle on edge runtimes → Valibot
  • Already using Effect for business logic → Effect Schema
  • Heavy tRPC or React Hook Form usage, need maximum documentation and hiring velocity → Zod

Most production codebases I have reviewed in 2024 chose Zod and have not regretted the decision. The patterns shown above scale from early-stage startups to services handling millions of daily requests.

By treating schemas as first-class contracts rather than scattered validation code, teams reduce both runtime errors and the cognitive load required to understand data expectations across frontend, backend, and external consumers. The combination of z.infer, reusable schema libraries, targeted refinements, and clean error mapping creates a validation layer that is simultaneously strict, maintainable, and fast enough for production use.

Keep reading

Related Research