0Pricing
React Academy · Lesson

Type-Safe Forms & API Response Contracts

Use Zod to infer TypeScript types from schemas and validate both form data and API responses.

Type-Safe Forms & API Response Contracts is a free React Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Type-Safe Data Shapes Matter

Forms and API responses are boundaries where data enters your application from untrusted sources. Zod lets you define schemas that both validate at runtime and infer TypeScript types.

Zod Schema Basics

Define schemas with Zod's fluent API. Use z.infer<typeof schema> to extract the TypeScript type.

import { z } from 'zod';

const UserSchema = z.object({
  id: z.string().uuid(),
  name: z.string().min(1).max(100),
  email: z.string().email(),
  age: z.number().int().min(0).max(150).optional(),
  role: z.enum(['admin', 'user', 'guest']),
});

type User = z.infer<typeof UserSchema>;
// { id: string; name: string; email: string; age?: number; role: 'admin'|'user'|'guest' }

React Hook Form with Zod Resolver

Integrate Zod schemas with React Hook Form for type-safe form validation — TypeScript knows the shape of form data and errors.

import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

const LoginSchema = z.object({
  email: z.string().email('Invalid email'),
  password: z.string().min(8, 'At least 8 characters'),
});
type LoginData = z.infer<typeof LoginSchema>;

function LoginForm() {
  const { register, handleSubmit, formState: { errors } } = useForm<LoginData>({
    resolver: zodResolver(LoginSchema),
  });

  const onSubmit = (data: LoginData) => {
    // data is LoginData — fully typed, already validated
  };
}

Validating API Responses

Parse API responses with Zod to catch shape mismatches at the boundary — if the API returns unexpected data, you get a detailed error instead of a runtime crash deep in your component.

async function fetchUser(id: string): Promise<User> {
  const res = await fetch(`/api/users/${id}`);
  const json = await res.json();
  return UserSchema.parse(json); // throws ZodError if shape is wrong
}

Safe Parse for Graceful Errors

Use schema.safeParse() to get a result object instead of throwing — ideal for form validation where you want to show errors to the user.

const result = UserSchema.safeParse(formData);
if (!result.success) {
  const errors = result.error.flatten().fieldErrors;
  // { name: ['Must be at least 1 character'], email: ['Invalid email'] }
  return errors;
}
const user = result.data; // User — fully typed

Discriminated Unions with Zod

Use z.discriminatedUnion to model API responses that have different shapes based on a success/error flag.

const ApiResponse = z.discriminatedUnion('ok', [
  z.object({ ok: z.literal(true), data: UserSchema }),
  z.object({ ok: z.literal(false), error: z.string(), code: z.number() }),
]);

type ApiResult = z.infer<typeof ApiResponse>;
// { ok: true; data: User } | { ok: false; error: string; code: number }

Zod Transformations

Use .transform() to coerce or reshape data during parsing — e.g., convert a date string to a Date object.

const DateSchema = z.string().transform(s => new Date(s));
// Input: '2024-01-15' → Output: Date object

const EventSchema = z.object({
  title: z.string(),
  date: z.string().pipe(z.coerce.date()),
});
type Event = z.infer<typeof EventSchema>;
// { title: string; date: Date }

Reusing Schemas

Derive creation and update schemas from the base schema to avoid duplication.

const UserSchema = z.object({ name: z.string(), email: z.string().email() });

// For creation: add password
const CreateUserSchema = UserSchema.extend({ password: z.string().min(8) });

// For update: all fields optional
const UpdateUserSchema = UserSchema.partial();

type CreateUser = z.infer<typeof CreateUserSchema>;
type UpdateUser = z.infer<typeof UpdateUserSchema>;

Server Action with Zod

Validate form data in a Next.js Server Action with Zod before hitting the database.

async function createPost(formData: FormData) {
  'use server';
  const schema = z.object({ title: z.string().min(3), body: z.string().min(10) });
  const result = schema.safeParse(Object.fromEntries(formData));
  if (!result.success) return { errors: result.error.flatten().fieldErrors };
  await db.post.create({ data: result.data });
  revalidatePath('/blog');
  redirect('/blog');
}

Shared Schemas Between Frontend and Backend

Export Zod schemas from a shared package so the frontend and backend use the same validation logic — one schema as the single source of truth.

// packages/schemas/src/user.ts
export const CreateUserSchema = z.object({ ... });
export type CreateUser = z.infer<typeof CreateUserSchema>;

// Frontend imports:
import { CreateUserSchema, CreateUser } from '@company/schemas';
// Backend imports:
import { CreateUserSchema } from '@company/schemas';

Zod Error Messages

Customize error messages per field for better UX — Zod passes them to the form's error display automatically via the resolver.

const RegistrationSchema = z.object({
  username: z.string()
    .min(3, 'Username must be at least 3 characters')
    .max(20, 'Username cannot exceed 20 characters')
    .regex(/^[a-z0-9_]+$/, 'Only lowercase letters, numbers, and underscores'),
});

Quick Check

What does z.infer provide in TypeScript?

Recap

Define Zod schemas once and use z.infer to derive TypeScript types. Use zodResolver in React Hook Form for type-safe validation. Parse API responses with Zod at the boundary, use safeParse for user-facing errors, and share schemas between frontend and backend via a shared package.

Frequently asked questions

Is the “Type-Safe Forms & API Response Contracts” lesson free?

Yes — the full text of “Type-Safe Forms & API Response Contracts” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Type-Safe Forms & API Response Contracts”?

Use Zod to infer TypeScript types from schemas and validate both form data and API responses. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Type-Safe Forms & API Response Contracts” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Discriminated Unions for Component Variants
  2. Conditional & Mapped Types in React
  3. Polymorphic Components with 'as' Prop
  4. Type-Safe Forms & API Response Contracts
← Back to React Academy