Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 6 · Lesson 53 · 7 min read

Typed API Client in React with Zod Validation

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A Schema, a Parsing Client and Safe Storage Reads
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain why TypeScript types alone do not protect against unexpected data at runtime, validate API responses and other untrusted inputs with Zod schemas, infer types from schemas, and design a client that reports contract violations usefully instead of crashing the interface.

Concept Explanation

On Day 30 you generated TypeScript types from the OpenAPI document, which makes the compiler check your calls against the contract. That protects you at build time, but TypeScript types are erased when the code compiles, so at runtime nothing verifies that the JSON that arrived actually has the promised shape. A response object typed as Note is simply whatever the network delivered. If the server has a bug, a proxy returns an HTML error page with a 200 status, a cached response from an older version is served, or the payload has been tampered with, the value flows into your components as if it were valid, and the failure appears far away as undefined is not a function.

Runtime validation closes that gap. Zod is a schema library for TypeScript: you describe a shape once, and it both validates unknown data at runtime and infers the static type from the same definition, so the two cannot drift. Applied at the edge of your application, in the client wrapper, it converts unpredictable network data into either a correctly typed value or a clear, catchable error. It is the client-side counterpart of the request validation you wrote on the server in Day 14, and it embodies the same principle: data crossing a trust boundary is unverified until checked.

There are several places where unvalidated data enters a React application besides API responses. Values read back from localStorage or sessionStorage may have been edited by the user or written by an older version of your code. URL search parameters and route parameters come straight from the address bar and can be crafted by anyone who sends a link. Messages received through postMessage or from a WebSocket arrive from other windows and services. Parsing each of these with a schema turns a class of subtle bugs and some injection-style attacks into predictable validation errors. OWASP names the general risk, trusting data from third-party APIs without validating it, as unsafe consumption of APIs, number ten in its list.

Design the client with a stance on failure. A schema mismatch on a critical response should not crash the whole page; report it to your error tracker with the endpoint and the trace identifier, then show a friendly error state. For non-critical fields, lenient parsing with defaults or the catch modifier keeps the interface working when the server adds or omits optional data. Be strict where it matters, such as identifiers, permissions, and money, and lenient where the cost of a mismatch is only cosmetic. Also transform on the way in: ISO date strings become Date objects, and unknown enum values map to a safe fallback, so components receive well-formed data and never repeat this cleanup.

Data sourceRiskValidation approach
API responseServer bug, proxy page, old cache, tamperingParse with a schema in the client wrapper
localStorage and sessionStorageUser edits, old app versionsParse on read, discard on failure
URL params and search stringCrafted linksSchema with coercion and limits
postMessage and WebSocketUntrusted sendersCheck origin, then parse the payload
Form inputAnything the user typesSame schema as the submit payload
Generated OpenAPI typesCompile-time onlyCombine with runtime schemas for critical data

Worked Example: A Schema, a Parsing Client and Safe Storage Reads

The schemas describe the notes API responses. The client helper parses and reports errors. The last snippet validates a value read from localStorage.

TypeScript
// src/api/schemas.ts
import { z } from 'zod';

export const NoteSchema = z.object({
  id: z.number().int().positive(),
  title: z.string().min(1).max(200),
  body: z.string().max(10_000).nullable(),
  updatedAt: z.iso.datetime({ offset: true }).transform((s) => new Date(s)),   // string in, Date out
  status: z.enum(['todo', 'inProgress', 'done']).catch('todo'),                 // unknown values fall back safely
});
export type Note = z.infer<typeof NoteSchema>;                                 // the type comes from the schema

export const PageSchema = <T extends z.ZodTypeAny>(item: T) =>
  z.object({ items: z.array(item), nextCursor: z.string().nullable() });

export const ProblemSchema = z.object({
  title: z.string().optional(),
  status: z.number().optional(),
  detail: z.string().optional(),
  traceId: z.string().optional(),
  errors: z.record(z.string(), z.array(z.string())).optional(),
});
Shell
// src/api/client.ts
export class ContractError extends Error {
  constructor(public endpoint: string, public issues: z.core.$ZodIssue[], public traceId?: string) {
    super(`Response from ${endpoint} did not match the expected shape`);
  }
}

export async function request<S extends z.ZodTypeAny>(
  url: string, schema: S, init: RequestInit = {},
): Promise<z.infer<S>> {
  const res = await fetch(url, { credentials: 'include', ...init });
  const traceId = res.headers.get('X-Correlation-Id') ?? undefined;

  if (!res.ok) {
    const problem = ProblemSchema.safeParse(await res.json().catch(() => ({})));
    throw new ApiError(res.status, problem.success ? problem.data : {}, traceId);
  }

  const parsed = schema.safeParse(await res.json());
  if (!parsed.success) {
    reportError(new ContractError(url, parsed.error.issues, traceId));   // to your error tracker, with the trace id
    throw new ContractError(url, parsed.error.issues, traceId);
  }
  return parsed.data;
}

// Usage: the result is typed AND verified.
const page = await request('/api/notes?pageSize=25', PageSchema(NoteSchema));
JavaScript
// Local storage can be edited by the user or written by an older release: parse, do not trust.
const PrefsSchema = z.object({ theme: z.enum(['light', 'dark']).default('light'), pageSize: z.number().int().min(5).max(100).default(25) });

export function loadPrefs() {
  try {
    const raw = localStorage.getItem('prefs');
    return PrefsSchema.parse(raw ? JSON.parse(raw) : {});
  } catch {
    return PrefsSchema.parse({});                    // corrupted or tampered: fall back to defaults
  }
}

// URL parameters: coerce and bound them before use.
const SearchParams = z.object({
  q: z.string().max(100).optional(),
  page: z.coerce.number().int().min(1).max(10_000).default(1),
});
const params = SearchParams.parse(Object.fromEntries(new URLSearchParams(location.search)));

Notice the split between strictness and leniency: the note identifier and title must be valid or the response is rejected, while an unknown status value degrades to a default. Reporting the schema issues together with the trace identifier lets you match a client-side failure with the server log line that produced it.

API responses, localStorage, URL parameters and postMessage all arrive as unverified data. A Zod schema parses each into a typed value or a reported error, so bad data never reaches components.
API responses, localStorage, URL parameters and postMessage all arrive as unverified data. A Zod schema parses each into a typed value or a reported error, so bad data never reaches components.

Real-World Examples

  • Zod was created by Colin McDonnell in 2020 to solve TypeScript's runtime blind spot, and it became one of the most widely used validation libraries in the ecosystem, used by tools such as tRPC and by form libraries through resolvers. Its central idea, one schema that yields both validation and a static type, is now common across libraries in other languages.
  • OWASP's API Security Top 10 2023 lists Unsafe Consumption of APIs as API10, observing that developers tend to trust data from third-party APIs more than user input and so apply weaker validation, which attackers exploit by compromising the third party. A frontend that parses every response with a schema applies the same skepticism to its own backend and to anything that reaches it through a proxy.
Key TakeawaysTypeScript types vanish at runtime, so validate every value that crosses a trust boundary: API responses, local storage, URL parameters, and messages. Use Zod schemas to get both verification and inferred types, be strict for identifiers and money and lenient for cosmetic fields, and report contract violations with the trace identifier instead of letting them crash the page.

Review Questions & Answers

Compile-time types only verify that your code is consistent with the contract, not that the data received matches it. A misbehaving server, an HTML error page, a stale cache, or tampering can deliver a different shape at runtime, and nothing in the compiled JavaScript would notice. A schema check turns those cases into explicit errors at the boundary.

The schema is the single definition, so the validator and the static type cannot diverge. With an interface plus a hand-written check, someone can update one and forget the other, leaving the type claiming a guarantee the runtime does not enforce. Inference also removes duplicate code.

Users can edit storage through the developer tools, extensions can modify it, and older versions of your application may have written different shapes. Blindly trusting the value can crash the interface or, if it feeds into security-relevant behavior, be exploited. Parsing with a schema and falling back to defaults on failure makes reads safe.

Be lenient for fields whose absence or unexpected value only affects presentation, such as an unknown status label falling back to a default, so a minor server change does not break the page. Be strict for identifiers, permissions, and money, where accepting a malformed value could cause wrong behavior or a security problem.