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.
- How to validate responses in
setResponseMapperand infer types from the schema. - How to validate payloads before they are sent with
setRequestMapper. - How to tell validation errors from API errors.
- 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.
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.
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.
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
| Where | Catches | Use it when |
|---|---|---|
setResponseMapper | An API that changed or returns bad data | You do not control the API, or it is critical data |
setRequestMapper | Invalid payloads from any caller | Several places send the request |
The form, before send() | Invalid input as the user types | You 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.
You've learned how to validate data with mappers.
- You can validate responses in
setResponseMapperand get types from the schema. - You can block invalid payloads in
setRequestMapperbefore they are sent. - You can tell a
ZodErrorfrom an API error withinstanceof.
Runnable examples: Payload validation and Response mapping.