Runtime Validation with Zod and TypeScript
On this page
Learning Objective
Identify the trust boundaries where untyped data enters a frontend, validate it at run time with a schema library such as Zod, infer static types from the schema so validation and types never diverge, and handle validation failures in API responses, URLs, storage and forms gracefully.
Concept Explanation
Day 41 established that TypeScript types are erased: they describe what you expect, not what you receive. Every frontend has boundaries where data arrives with no guarantees. API responses can change shape after a backend deploy, return an error format you did not expect or contain nulls where you assumed values. URL parameters are typed by users. localStorage may hold data written by an older version of your app. Messages from WebSockets, postMessage, third-party scripts and file uploads are all untrusted. Writing as User after JSON.parse does not check any of this; it only silences the compiler.
Runtime validation closes the gap by checking data against a schema when it crosses a boundary. Schema libraries such as Zod, Valibot, ArkType and Yup let you describe the expected shape in code: an object with a string email, a number between 1 and 100, an enum of statuses. Parsing returns typed data if the input conforms, or a structured error listing every problem and its path if it does not. Validation happens once, at the edge, and everything inside the application can trust the types.
The key technique is to derive the TypeScript type from the schema, with z.infer, rather than writing both. Then there is one definition, and the static type and the runtime check can never disagree. Schemas also transform: they can coerce strings from URLs to numbers, trim input, parse ISO date strings into Date objects and apply defaults, so the shape your components consume is cleaner than the shape on the wire. Separating the input type from the output type lets an API's raw format differ from your domain model.
Decide what should happen on failure for each boundary. For API responses, safeParse lets you log the mismatch with its details to your monitoring and show a friendly error instead of crashing deep inside a component with "cannot read properties of undefined". For URL parameters, fall back to defaults. For stored data, discard it or migrate it. For forms, map the errors back to fields, and share the same schema with a Node backend when possible so both sides enforce identical rules (Day 68). Validation on the client never replaces validation on the server; it protects the client from bad data and gives users fast feedback.
There is a cost: schemas add bundle size and parsing time. For most apps it is negligible, but for very large responses you might validate only the fields you use, validate in development and sample in production, or prefer a smaller library such as Valibot. Generating schemas or types from an OpenAPI specification is another way to keep frontend and backend contracts aligned.
| Boundary | Risk | Validation response |
|---|---|---|
| API responses | Shape changes after deploys | safeParse, report, show error state |
| URL search params | Typed or edited by users | Coerce, default on failure |
| localStorage and IndexedDB | Old versions of your data | Discard or migrate |
| postMessage and WebSockets | Any origin or sender | Check origin, then validate |
| Form input | User mistakes | Field errors, same schema as server |
| Environment variables | Missing configuration | Fail fast at startup |
| Third-party scripts | Unexpected values | Validate before use |
Worked Example: One Schema for Types, API Parsing and URL Filters
The order schema validates API responses and produces the TypeScript type. The filter schema turns untrusted URL parameters into safe, typed values with defaults.
import { z } from 'zod';
// One schema: the runtime check and the static type
const OrderSchema = z.object({
id: z.string().min(1),
status: z.enum(['pending', 'paid', 'shipped', 'cancelled']),
totalCents: z.number().int().nonnegative(),
placedAt: z.string().datetime().transform((s) => new Date(s)), // wire string, domain Date
customer: z.object({ name: z.string(), email: z.string().email() }),
note: z.string().nullable().default(null),
});
export type Order = z.infer<typeof OrderSchema>; // placedAt is a Date
const OrdersResponse = z.object({ items: z.array(OrderSchema), nextCursor: z.string().nullable() });
export async function fetchOrders(cursor?: string) {
const res = await fetch(`/api/orders${cursor ? `?cursor=${cursor}` : ''}`);
if (!res.ok) throw new Error(`Orders failed with ${res.status}`);
const parsed = OrdersResponse.safeParse(await res.json());
if (!parsed.success) {
reportError(new Error('Orders response did not match the schema'), { issues: parsed.error.issues });
throw new Error('We received unexpected data. Please try again later.');
}
return parsed.data; // fully typed and trusted
}
// URL filters: coerce strings, clamp values, never throw on bad input
const FiltersSchema = z.object({
page: z.coerce.number().int().min(1).catch(1),
pageSize: z.coerce.number().int().min(10).max(100).catch(20),
status: z.enum(['pending', 'paid', 'shipped', 'cancelled']).optional().catch(undefined),
q: z.string().trim().max(100).optional().catch(undefined),
});
export type Filters = z.infer<typeof FiltersSchema>;
export function readFilters(search: string): Filters {
return FiltersSchema.parse(Object.fromEntries(new URLSearchParams(search)));
}
readFilters('?page=-3&pageSize=5000&status=hacked&q= boots ');
// { page: 1, pageSize: 20, status: undefined, q: 'boots' }If the backend renames totalCents, the failure is reported once, at the boundary, with the exact path and issue, instead of surfacing as NaN prices across a dozen components.
Real-World Examples
- Zod became one of the most downloaded TypeScript libraries on npm and is the validation layer recommended or integrated by tRPC, React Hook Form resolvers, the T3 stack and Astro's content collections, all of which rely on inferring types from schemas.
- The OWASP Input Validation Cheat Sheet recommends validating all data from untrusted sources using allowlists of expected formats as early as possible, a principle that applies equally to data a frontend receives from APIs, URLs and storage.
Review Questions & Answers
A type assertion only tells the compiler to assume the type; nothing checks the actual data at run time. If the server sends a different shape, the code proceeds with wrong assumptions and fails later, far from the cause.
There is a single definition that serves both as the runtime validator and the static type, so they cannot drift apart. Changing the schema automatically changes the type everywhere it is used.
Gracefully, by coercing strings to the expected types, clamping values to allowed ranges and falling back to defaults when a value is invalid, rather than throwing. Users edit URLs and follow old links, and a bad parameter should never break the page.
No. Client validation gives fast feedback and protects the client from bad data, but anyone can bypass the client. The server must validate every request independently, ideally using the same schema so the rules match.