API Response Parsing
External APIs can change shape without warning. Parsing the response through a Zod schema at the boundary means any breaking change surfaces as a clear validation error rather than a mysterious undefined deep in your code. Try removing total or changing published to a string.
import { z } from 'zod';
const PostSchema = z.object({
id: z.number(),
title: z.string(),
published: z.boolean(),
});
const ApiResponseSchema = z.object({
data: z.array(PostSchema),
total: z.number(),
});
const raw = await fetch('/api/posts').then(r => r.json());
const response = ApiResponseSchema.parse(raw);type Post = {
id: number;
title: string;
published: boolean;
};
type ApiResponse = {
data: Post[];
total: number;
}{
"data": [
{
"id": 1,
"title": "Getting started with Zod",
"published": true
},
{
"id": 2,
"title": "Advanced patterns",
"published": false
}
],
"total": 2
}