TIL NOTE #022
Type Your API Responses, Not Just Your Requests
The mistake:
// ✗ Validates input carefullyconst res = await fetch("https://api.example.com/users", { method: "POST", body: JSON.stringify(validated_user)});
// ✗ Just casts as anyconst data = (await res.json()) as User;API changes its schema. Your type is now wrong. Crash in production.
The fix: Parse responses with zod.
const UserSchema = z.object({ id: z.string(), email: z.string().email(), name: z.string()});
const res = await fetch("https://api.example.com/users");const data = UserSchema.parse(await res.json()); // Throws if invalidIf the API returns a field you don’t expect, or removes one you do, the error is immediate and loud.
Trust nothing from external systems. Validate responses the same way you validate inputs.