DevHuzaifa's Portfolio
•3 min read•Updated Oct 31, 2026

TypeScript Ends at the Network: Validating API Data with Zod

Type annotations do not validate JSON. Build a Zod schema at the API boundary, handle validation failures, and distinguish input types from parsed output.

#Typescript#Zod Schemas#Code Patterns

A fetch call returns JSON. A TypeScript assertion labels it User. Your component reads user.name, and production crashes because the API returned null. The compiler checked your code against an assumption; it never checked the response against a contract.

External JSON enters a Zod schema and becomes validated application data, while invalid input follows an error path.

Zod moves that contract into runtime code. Define the shape once, parse external input at the boundary, and let application code consume the parsed result. These examples use Zod 4 and a browser-compatible fetch environment.

The Problem: A Type Assertion Is Not Validation

typescript
type User = { id: string; name: string };

const response = await fetch('/api/me');
const user = await response.json() as User;
// This assertion does not inspect the returned value.
console.log(user.name.toUpperCase());

An internal API can still drift during a deployment, return an error payload, or contain unexpected legacy data. Make the boundary explicit so the resulting error is local to the request instead of surfacing deep inside a component tree.

Step 1: Define the Runtime Contract

typescript
import * as z from 'zod';

export const UserSchema = z.object({
  id: z.string().min(1),
  name: z.string().trim().min(1),
});

export type User = z.infer<typeof UserSchema>;

The schema expresses the application’s required shape. This example requires nonempty strings and normalizes whitespace around the name. Decide which extra fields are acceptable for your boundary; Zod also offers strict object schemas when unknown keys should be rejected.

Step 2: Parse Before Returning from the API Client

typescript
export async function fetchCurrentUser(): Promise<User> {
  const response = await fetch('/api/me');
  if (!response.ok) {
    throw new Error('Unable to load the current user');
  }

  const payload: unknown = await response.json();
  const result = UserSchema.safeParse(payload);

  if (!result.success) {
    throw new Error('The user response has an unexpected shape');
  }
  return result.data;
}

HTTP failures, malformed JSON, and invalid object shapes are different failure points. Give the UI a useful fallback and give monitoring enough context to identify which boundary failed. Avoid dumping entire private response payloads into logs.

safeParse returns a success/error result instead of throwing for ordinary validation failures. parse is equally valid when your error handling deliberately uses exceptions. With asynchronous refinements or transforms, choose the corresponding asynchronous parsing API.

Step 3: Separate Raw Input from Parsed Output

typescript
const PageSchema = z.string()
  .regex(/^[1-9]\d*$/, 'Use a positive whole number')
  .transform(Number)
  .pipe(z.number().int().min(1).max(1000));

type PageInput = z.input<typeof PageSchema>;   // string
type PageOutput = z.output<typeof PageSchema>; // number

const page = PageSchema.parse('12'); // 12

A URL parameter begins as text. Validate its accepted syntax before converting it, then validate the resulting numeric range. This makes values such as an empty string or an unexpectedly large page number take an explicit error path.

Transforms can make the raw input type different from the parsed output type. Use z.input and z.output when a form or request adapter needs to describe both sides of that boundary.

What Deserves a Schema

Prioritize external inputs: HTTP responses, webhook bodies, form submissions, and configuration. Parsing every value between trusted internal functions often adds repetition without improving the boundary. Put the contract near the code that receives the data, then reuse its inferred output type.

Validation also does not establish authorization or verify that an identifier exists in the database. A structurally valid request still needs the application’s business checks. Keep those responsibilities visible rather than forcing every rule into one schema.

Related: Zod Of Thunder!

Zod basic parsing and error handling

Zod schemas, transforms, and pipes

TypeScript type assertions are erased at compilation