Skip to main content
Version: v10.5.0

API response and request validation with Zod

TypeScript types describe what you expect from an API, but they do not check what arrives at runtime. Validation does: a mapper parses the data with a schema, and when it throws, HyperFetch turns the throw into an error response. This guide validates responses and payloads with Zod, and the same works with any schema library.

What you'll learn
  1. How to validate responses in setResponseMapper and infer types from the schema.
  2. How to validate payloads before they are sent with setRequestMapper.
  3. How to tell validation errors from API errors.
  4. When to validate in the form instead.

Validate the response​

Parse data in setResponseMapper and return the parsed value. A failed parse throws a ZodError, and send() resolves with it in error. Returning the parsed value also applies Zod's transforms and strips unknown keys.

src/api/users.ts
import { z } from "zod";

const UserSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
createdAt: z.string().transform((value) => new Date(value)),
});

export const getUser = client
.createRequest<{ response: z.input<typeof UserSchema> }>()({
endpoint: "/users/:userId",
})
.setResponseMapper((response) => {
if (!response.data) return response;
return { ...response, data: UserSchema.parse(response.data) };
});

const { data } = await getUser.send({ params: { userId: 1 } });
// data: { id: number; name: string; email: string; createdAt: Date } | null

The response generic is the raw shape (z.input), and data gets the parsed shape (z.output) from the mapper. The cache keeps the raw response, and the mapper validates it again on every delivery.


Validate the payload​

Parse the payload in setRequestMapper. When it throws, the request is not sent and send() resolves with the ZodError, so invalid data never reaches the server.

src/api/posts.ts
const PostInput = z.object({
title: z.string().min(3, "Title must be at least 3 characters"),
body: z.string().min(10, "Body must be at least 10 characters"),
});

export const createPost = client
.createRequest<{
response: { id: number };
payload: z.infer<typeof PostInput>;
}>()({
endpoint: "/posts",
method: "POST",
})
.setRequestMapper((request) => {
PostInput.parse(request.payload); // throws a ZodError for invalid data
return request;
});

Tell validation errors apart​

A ZodError is an Error, so check it with instanceof before reading your API's error shape.

src/post-form.ts
const { data, error } = await createPost.send({
payload: { title: "Hi", body: "Too short" },
});

if (error instanceof z.ZodError) {
// Not sent: show the field messages
showFieldErrors(error.flatten().fieldErrors);
} else if (error) {
showToast("Could not save the post");
} else {
navigate(`/posts/${data?.id}`);
}

Where to validate​

WhereCatchesUse it when
setResponseMapperAn API that changed or returns bad dataYou do not control the API, or it is critical data
setRequestMapperInvalid payloads from any callerSeveral places send the request
The form, before send()Invalid input as the user typesYou want messages before submit

Validate the form before send() for the best UX, and keep the request mapper as the last guard. Parsing large responses on every delivery has a cost: validate the fields you rely on, or validate in development only.


Congratulations!

You've learned how to validate data with mappers.

  • You can validate responses in setResponseMapper and get types from the schema.
  • You can block invalid payloads in setRequestMapper before they are sent.
  • You can tell a ZodError from an API error with instanceof.

Runnable examples: Payload validation and Response mapping.

Mapping
Async mappers, class models and mapper order.
Error handling
Kinds of errors and how to type them.
Request
Map and validate on the request.