State & ArchitectureBaseline · Widely

Runtime Boundary Validation (Parse, Don't Validate)

Mental Model

TypeScript types vanish at compile time, leaving fetch(), postMessage(), and localStorage free to inject undefined fields into state. Parsing untrusted payloads at the I/O boundary converts unknown into a guaranteed shape or fails explicitly before corrupted data reaches UI components.

Interactive Simulator

Unsafe Type Assertion vs Runtime Boundary Parsing

Compare compile-time type casting against safeParse boundary enforcement on untrusted API payloads.

Lines of Code
Before
3
After
5
Reflows / Browser Cost
Before
Uncaught TypeError crashes entire tree
After
Isolated fallback UI on drift
BeforeBlind Type Cast (Runtime Drift Uncaught)
const user = (await res.json()) as { profile: { name: string } };
// Crashes deep in React render if backend omits profile:
return <span>{user.profile.name.toUpperCase()}</span>;
Lines: 3Reflows: Uncaught TypeError crashes entire treeDependencies: 0 KB runtime, zero safety

TypeScript passes at build time, then throws TypeError in production when API shape drifts.

After (Native)Boundary Parser (Fail Explicit at I/O)
const parsed = UserSchema.safeParse(await res.json());
if (!parsed.success) {
  return reportSchemaDrift(parsed.error);
}
return <span>{parsed.data.profile.name.toUpperCase()}</span>;
Lines: 5Reflows: Isolated fallback UI on driftDependencies: 1-12 KB schema parser (Valibot/Zod)

Corrupted payloads are quarantined at the fetch boundary before touching UI state.

Under the Hood

Every JSON.parse() call and Structured Clone boundary returns unknown at runtime. Boolean validate(x) checks discard proof of structure, whereas a parser refines the type and strips unexpected keys in one pass.

  1. Boundary isolation: Run schema parsing once in the network, storage, or Worker adapter rather than inside render functions.
  2. Non-throwing safeParse: Return a discriminated { success, data | error } result so corrupted localStorage entries fall back to defaults instead of crashing hydration.
  3. Chunked large lists: Offload multi-megabyte array parsing to a Dedicated Worker or validate lazily to avoid Long Tasks.
TS
import { z } from 'zod';

const UserSchema = z.object({ id: z.string(), role: z.enum(['admin', 'viewer']) });
type User = z.infer<typeof UserSchema>;

export async function fetchUser(url: string): Promise<User> {
  const raw: unknown = await (await fetch(url)).json();
  const parsed = UserSchema.safeParse(raw);
  if (!parsed.success) throw new Error(`Schema drift: ${parsed.error.message}`);
  return parsed.data;
}

Problem Genealogy

  • 2016–2019 (TypeScript res.json() as T): Teams trusted backend contracts via blind casts, causing uncatchable Cannot read properties of undefined crashes weeks after API deploys.
  • 2019 ("Parse, Don't Validate"): Formalized type-driven parsing so downstream code never re-checks invariants.
  • 2021+ (Zod, Valibot & Standard Schema): Compressed schema validators to 1–12 KB gzipped with zero-cost TypeScript inference.

Production Pitfalls

Production Pitfall
  • White-screen crash on stale localStorage schema: Deploying a renamed field without safeParse fallback throws during initial state hydration for returning users.
  • 50 ms+ main-thread stall on 5,000-row tables: Running deep recursive object validation synchronously inside a click handler blocks paint frames and spikes INP.
When Not to Use
  • When not to use runtime schema parsing: Inside 60 fps animation loops, requestAnimationFrame physics ticks, or already-parsed internal reducer transitions where data never crossed an untrusted serialization boundary.

Connections & Logical Next Steps

State & ArchitectureRuntime Boundary Validation (Parse, Don't Validate)
What This Unlocks
Leaf concept

Seen in Architecture Autopsies