Zod 23 🛡️ React Query Integration — Parsing API responses with schemas before caching
React Query caches whatever the queryFn returns. If the function returns raw response.json(), the cache holds unvalidated data, and every component that reads it trusts a type that was never checked at runtime. The Zod schema is the gate: it runs inside the queryFn, before the data enters the cache, so a malformed response becomes a query error rather than a component crash . The pattern is mechanical—fetch, parse, return—but the placement matters. Parsing in the component or in a select callback runs after the cache, which means the invalid data is already stored and shared.
This chapter covers the queryFn parse pattern, the safeParse versus parse decision for query errors, and the select option that validates and transforms after caching when the transformation is expensive or the raw payload must be preserved. The sections that follow walk through the basic integration, the error-handling variants, and the edge cases around enum evolution and schema drift.
Key point: Parse inside the queryFn so invalid data never enters the cache; use safeParse if you want a custom error shape, parse if you want the ZodError to surface as the query error, and reserve select for transformations that should not affect what is cached.
a. The queryFn parse pattern
The queryFn returns a Promise of the parsed type. The schema runs after response.json() and before the value is returned, so React Query caches the parsed output, not the raw JSON . The type inference flows from the schema: useQuery infers data as z.infer<typeof Schema>, and there is no separate type annotation to maintain.
import { useQuery } from "@tanstack/react-query";
import { z } from "zod";
const UserSchema = z.object({
id: z.string().uuid(),
name: z.string(),
email: z.email(),
createdAt: z.string().datetime(),
});
type User = z.infer<typeof UserSchema>;
async function fetchUser(id: string): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
return UserSchema.parse(data); // throws ZodError if invalid
}
function useUser(id: string) {
return useQuery({
queryKey: ["users", id],
queryFn: () => fetchUser(id),
enabled: !!id, // conditional fetch
});
}
The parse call throws a ZodError on failure, and React Query catches it as the query’s error . The data in the component is typed as User, and the error is a ZodError if the contract was violated, or an Error if the HTTP request failed. The distinction is visible in the error property, and a component can branch on error instanceof ZodError if it wants to log the issues differently from a network failure.
The query key should include the parameters that affect the response, so invalidation is predictable. A key of ["users", id] means invalidateQueries({ queryKey: ["users"] }) refetches every user, while invalidateQueries({ queryKey: ["users", id] }) refetches only one .
b. safeParse and custom error handling
parse throws the ZodError with its issues array intact. If the application needs a domain-specific error—a ContractError with a user-facing message and the issues attached—safeParse returns the result and the code constructs the error explicitly.
class ContractError extends Error {
constructor(public readonly issues: z.ZodIssue[]) {
super("The server returned data that does not match the contract.");
this.name = "ContractError";
}
}
async function fetchUser(id: string): Promise<User> {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const result = UserSchema.safeParse(data);
if (!result.success) {
throw new ContractError(result.error.issues);
}
return result.data;
}
The safeParse variant is the correct choice when the error type matters to the UI—a component that distinguishes “server contract broken” from “network down” needs the two errors to be different classes. The parse variant is the correct choice when the ZodError itself is the error and the component logs error.issues directly.
The choice should not be “always parse” or “always safeParse.” The question is whether the caller needs the error to be a specific type. If not, parse is shorter and the ZodError carries the same information .
c. select for post-cache transformations
React Query’s select option runs after the queryFn returns and after the data is cached. It transforms the cached value into the shape the component needs, without changing what is stored . This is the correct place for expensive computations or for mapping a DTO to a domain object, but it is not the place for validation, because validation in select means the invalid data was already cached and shared with every other consumer of the same query key.
function useUserNames() {
return useQuery({
queryKey: ["users"],
queryFn: () => fetchUsers(), // returns User[] (validated)
select: (users) => users.map((u) => u.name), // derived, not validated
});
}
The select function runs on every render that reads data, but the result is memoized and only recomputes when the cached data changes. For a transformation that is pure and cheap, select is the right tool; for validation, it is the wrong layer.
The tanstack-query-json-api package documents this pattern explicitly: the Zod schema is used in the select function to both validate and transform, and the transformed result is cached as long as the server responds with the same JSON body . That is a valid design when the raw JSON is not intended to be consumed directly and the transformation is the point. It is not the pattern for a cache that should hold validated data for multiple consumers.
Complete Example Session
// ============================================
// PART 1: THE SCHEMA
// ============================================
import { z } from "zod";
const PostSchema = z.object({
id: z.number().int().positive(),
title: z.string().min(1),
body: z.string(),
tags: z.array(z.string()),
publishedAt: z.string().datetime().nullable(),
});
type Post = z.infer<typeof PostSchema>;
// ============================================
// PART 2: THE QUERY FUNCTION WITH PARSE
// ============================================
async function fetchPost(id: number): Promise<Post> {
const res = await fetch(`/api/posts/${id}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return PostSchema.parse(await res.json());
}
// ============================================
// PART 3: THE HOOK (INFERRED TYPES)
// ============================================
import { useQuery } from "@tanstack/react-query";
function usePost(id: number) {
return useQuery({
queryKey: ["posts", id],
queryFn: () => fetchPost(id),
enabled: Number.isFinite(id),
staleTime: 60_000,
});
}
// data: Post | undefined
// error: Error | ZodError
// ============================================
// PART 4: SELECT FOR DERIVED DATA
// ============================================
function usePostTitle(id: number) {
return useQuery({
queryKey: ["posts", id],
queryFn: () => fetchPost(id),
select: (post) => post.title, // derived, not validated
});
}
// data: string | undefined
// ============================================
// PART 5: SAFEPARSE FOR CUSTOM ERROR
// ============================================
async function fetchPosts(): Promise<Post[]> {
const res = await fetch("/api/posts");
const raw = await res.json();
const result = z.array(PostSchema).safeParse(raw);
if (!result.success) {
throw new ContractError(result.error.issues);
}
return result.data;
}
The example covered the schema, the queryFn with parse, the hook with inferred types, the select derivation, and the safeParse variant with a custom error class.
Quick Reference
Integration Points
| Location | Validates | Caches | Use For |
|---|---|---|---|
queryFn | Yes | Parsed data | Default pattern |
select | Yes (but after cache) | Raw data | Post-cache transformation only |
| Component | Yes (but after cache) | Raw data | Never for security |
queryFn + safeParse | Yes | Parsed data | Custom error types |
Error Handling
| Pattern | Throws | Error Type |
|---|---|---|
Schema.parse(data) | ZodError | ZodError |
safeParse + throw | Custom class | ContractError |
response.ok check | Error | Error |
Query Key Rules
| Key | Invalidates |
|---|---|
["posts"] | All posts |
["posts", id] | One post |
["posts", id, "comments"] | Comments of one post |
Best Practices
✅ Do This:
// Parse inside the queryFn
queryFn: async () => Schema.parse(await res.json()) // ✅
// Include params in the query key
queryKey: ["posts", id] // ✅
// Use select for derived data
select: (post) => post.title // ✅
// Use safeParse when a custom error class is needed
if (!result.success) throw new ContractError(result.error.issues); // ✅
❌ Don’t Do This:
// Parse in the component after caching
const { data } = useQuery(...);
Schema.parse(data); // already cached, other consumers unvalidated // ❌
// Use select for validation
select: (raw) => Schema.parse(raw) // cached data is raw // ❌
// Skip the HTTP error check
const data = await res.json(); Schema.parse(data); // 404 body may parse // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Invalid data in cache | Parse in component or select | Parse in queryFn |
| Enum parse failure on new value | Bare z.enum() in contract | Use fallback enum or z.string() |
Type says Date, runtime is string | No transform in schema | Add .transform() or z.coerce.date() |
| Query error not distinguishable | parse throws generic | Use safeParse + custom error class |
Real-World Examples
1. queryFn with parse
queryFn: async () => Schema.parse(await res.json());
2. safeParse with custom error
if (!result.success) throw new ContractError(result.error.issues);
3. select for derived data
select: (users) => users.map((u) => u.name);
4. Query key with params
queryKey: ["users", userId];
5. Conditional fetch
enabled: !!userId;
6. Array schema
z.array(UserSchema).parse(await res.json());
7. Enum fallback
z.enum(["a", "b"]).catch("a"); // v4
8. Date coercion
z.coerce.date();
9. Multiple consumers, one parse
Parse once in queryFn, cache holds validated data.
10. MSW handler with schema
Co-locate mock data with schemas in testUtils/
Visual
The Cache Boundary
┌─────────────────────────────────────────────────────────┐
│ fetch() → response.json() │
│ │ │
│ ▼ │
│ Schema.parse() ◄── THE GATE │
│ │ │
│ ┌────┴────┐ │
│ ▼ ▼ │
│ valid invalid │
│ │ │ │
│ ▼ ▼ │
│ cache ZodError │
│ (parsed) (query error) │
│ │
│ Invalid data never enters the cache │
└─────────────────────────────────────────────────────────┘
Parse vs Select
┌─────────────────────────────────────────────────────────┐
│ queryFn + parse │
│ Raw → Validate → Cache (validated) → Component │
│ │
│ queryFn + select │
│ Raw → Cache (raw) → Select (transform) → Component │
│ │
│ select cannot protect the cache; only queryFn can. │
└─────────────────────────────────────────────────────────┘
Error Types
┌─────────────────────────────────────────────────────────┐
│ parse → ZodError │
│ error instanceof ZodError → error.issues │
│ │
│ safeParse + throw → ContractError │
│ error instanceof ContractError → error.issues │
│ │
│ HTTP !ok → Error │
│ error.message → "HTTP 500" │
└─────────────────────────────────────────────────────────┘
Query Key and Invalidation
┌─────────────────────────────────────────────────────────┐
│ queryKey: ["posts", id] │
│ │
│ invalidateQueries({ queryKey: ["posts"] }) │
│ → refetches every post │
│ │
│ invalidateQueries({ queryKey: ["posts", id] }) │
│ → refetches one post │
│ │
│ Params in the key make invalidation predictable. │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Parse location | Inside queryFn |
| Cache contents | Parsed (validated) data |
| Error on parse failure | ZodError via parse, custom via safeParse |
select role | Post-cache transformation only |
| Query key | Include response-affecting params |
| Enum evolution | Use fallback enum, not bare z.enum() |
Key takeaways:
- Parse in the
queryFn, not in the component. The cache is shared across every consumer of the query key. Parsing after caching means one consumer may validate while another reads the raw data, and the cache holds the unvalidated version . parseandsafeParseserve different error needs.parsethrows aZodErrorthat carries the issues array.safeParselets the code throw a domain-specific error class, which is useful when the component distinguishes contract failures from network failures.selectis for derived data, not validation. It runs after the cache and transforms the cached value for the component. Validating inselectmeans the raw data is already cached and every other consumer is unprotected .- Query keys include the parameters that affect the response.
["users", id]makes invalidation predictable: invalidating["users"]refetches all, invalidating["users", id]refetches one . - Bare
z.enum()is a forward-compatibility risk. If the backend adds an enum value, old clients that parse with a strict enum will fail on the new value. Use a fallback enum orz.string()when the set is expected to grow .
Remember: React Query’s cache is a shared data store, and whatever enters it is trusted by every component that reads it. The queryFn is the only place where the data crosses from untrusted (network) to trusted (cache). Put the schema there. Use parse for the short path, safeParse when the error needs a custom shape, and select for transformations that should not change what is cached. The cache should hold validated data, not raw JSON waiting for a component to check it.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!