Generating Strict Zod Schemas from Untrusted JSON
Infer Zod object schemas from sample JSON payloads, tighten loose string/number rules into strict runtime contracts, and handle nullable fields cleanly.
On this page
Why TypeScript Interfaces Alone Fail at Runtime
TypeScript types vanish at compile time. When your Next.js API route, Fastify handler, or React client parses await response.json(), JSON.parse() returns any regardless of the TypeScript interface you cast it to. An upstream microservice returning "total": "42.50" instead of 42.5, omitting a nested address block, or introducing an extra billing state crashes downstream UI components or corrupts persisted records.
Zod bridges this runtime gap by letting one schema serve both as your runtime parser and your static TypeScript type via z.infer<typeof Schema>. Starting from a large, deeply nested third-party JSON payload and hand-typing 60 fields is tedious and error-prone. Generating an initial schema structurally from sample JSON gets the hierarchy right in seconds, after which your engineering work focuses on tightening domain bounds and edge cases.
Beyond catching outright crashes, strict schema validation protects your internal domain state from subtle drift. Suppose an analytics service begins returning strings instead of integers for retryCount, or adds a sentinel string "N/A" inside an array of timestamps. Without a boundary parser sitting right beside JSON.parse(), those malformed values propagate silently into React state, SQLite caches, or downstream billing aggregations, where debugging the root cause hours later takes ten times as long.
Inferring Baseline Schemas from Sample JSON
To bootstrap a baseline schema quickly without losing nested object shapes or union arrays, paste a scrubbed sample response into the Interactive JSON to Zod Converter. A clean generator inspects every primitive type, infers heterogeneous array items into z.union([...]), marks empty arrays clearly so you replace z.unknown(), and emits readable z.infer type exports.
Yet structural inference is only step one. An observed payload containing "role": "admin" looks like z.string(), even though your application strictly allows "admin" | "member" | "viewer". Similarly, "id": "7f3c..." might look like a generic string until you constrain it with .uuid(), and "age": 31 gives no clue whether negative floats should be rejected. Whenever you run schema inference over multiple captured samples rather than a single lucky snapshot, collect both happy-path payloads and rare edge states (such as canceled orders, partial refunds, and missing optional blocks) so your baseline type union reflects real-world polymorphism before you tighten constraints.
Hardening Generated Schemas for Production Boundaries
Consider a raw order webhook payload inferred initially by shape alone, then hardened into a defensive runtime contract. Notice how every primitive receives domain boundaries, strings reject unbounded lengths, and discriminators use z.discriminatedUnion for fast, clear error reporting.
import { z } from "zod";
// Hardened schema derived from sample JSON payload
export const PaymentEventSchema = z
.object({
eventId: z.string().uuid(),
occurredAt: z.string().datetime({ offset: true }),
currency: z.enum(["USD", "EUR", "GBP", "JPY"]),
amountCents: z.number().int().nonnegative().max(100_000_000),
customer: z
.object({
id: z.string().min(1).max(64),
email: z.string().email().max(254),
taxId: z.string().trim().max(32).nullable(),
})
.strict(),
items: z
.array(
z.object({
sku: z.string().regex(/^[A-Z0-9-]{4,32}$/),
quantity: z.number().int().min(1).max(10_000),
unitPriceCents: z.number().int().nonnegative(),
}),
)
.min(1)
.max(200),
metadata: z.record(z.string().max(40), z.string().max(256)).default({}),
})
.strict();
export type PaymentEvent = z.infer<typeof PaymentEventSchema>;
Look closely at three production defenses embedded above:
- Bounded strings and arrays: Unbounded
z.string()andz.array()let an attacker or buggy client pass a 50,000-item array or a 4MB string into your business logic. Adding.max()enforces structural sanity right at the ingress layer. - Exact
.nullable()versus.optional(): JSON hasnull, notundefined. When an external API sends"taxId": null,.optional()rejects it while.nullable()accepts it. Reserve.nullish()for inconsistent third-party APIs that sometimes omit a key and sometimes emitnull. - Explicit
.strict()vs.passthrough(): On internal form submissions or trusted RPC calls,.strict()immediately surfaces typoed client field names (such astax_idvstaxId) instead of silently dropping them. On evolving third-party webhooks where providers add fields frequently, drop.strict()on the outer envelope so Zod strips unknown properties without breaking ingestion.
Formatting Actionable Errors and Handling Coercion
Throwing schema.parse(raw) on untrusted input forces callers to catch ZodError exceptions on control flow. Prefer schema.safeParse(raw), map error.issues into stable field paths, and return structured 422 Unprocessable Entity payloads without echoing sensitive input values back to logs or clients.
export interface ValidationFailure {
status: 422;
errors: Array<{ path: string; code: string; message: string }>;
}
export function parseUntrustedJson<T extends z.ZodTypeAny>(
rawText: string,
schema: T,
): { ok: true; data: z.infer<T> } | { ok: false; failure: ValidationFailure } {
let parsed: unknown;
try {
parsed = JSON.parse(rawText);
} catch {
return {
ok: false,
failure: {
status: 422,
errors: [{ path: "$", code: "invalid_json", message: "Malformed JSON syntax" }],
},
};
}
const result = schema.safeParse(parsed);
if (!result.success) {
return {
ok: false,
failure: {
status: 422,
errors: result.error.issues.map((issue) => ({
path: issue.path.length > 0 ? issue.path.join(".") : "$",
code: issue.code,
message: issue.message,
})),
},
};
}
return { ok: true, data: result.data };
}
For HTML forms or query parameters where numbers arrive as strings, use z.coerce.number() cautiously: remember that in JavaScript Number("") === 0 and Number(" ") === 0! An empty query parameter ?limit= coerced via z.coerce.number() silently becomes 0 unless you preprocess empty strings to undefined first via z.preprocess((v) => (v === "" ? undefined : v), z.coerce.number().int().positive()).
Pitfalls with Unions, Dates, and Prototype Keys
Watch for subtle edge cases as schemas evolve:
- Order-dependent
z.union(): Regularz.union([SchemaA, SchemaB])tries variants sequentially and emits confusing aggregate errors if all fail. When variants share a tag likekind: "card" | "bank", switch toz.discriminatedUnion("kind", [...])for O(1) dispatch and crisp error diagnostics. - Unchecked
z.coerce.date():z.coerce.date()accepts numeric epoch timestamps and permissiveDate.parse()strings inconsistently across environments. When JSON carries ISO 8601 strings, validate explicitly withz.string().datetime({ offset: true })and convert inside.transform()only if downstream callers require aDateinstance. - Empty arrays in sample generation: Any sample JSON containing
"tags": []gives zero type evidence; always audit generated schemas forz.array(z.unknown())and replace them with concrete element schemas before committing. - Prototype pollution keys (
__proto__,constructor): Even whenJSON.parse()creates an object with"__proto__"as an own enumerable property, spreading validated output carelessly or merging into plain dictionaries downstream can mutate object prototypes if.passthrough()is enabled. Keep.strict()or default strip mode active onz.object(), and validate dynamic map keys explicitly when usingz.record().
Verifying Contract Coverage Before Deployment
Once you draft the schema with the Interactive JSON to Zod Converter and tighten its constraints, back it with adversarial unit tests. Assert that parseUntrustedJson succeeds on realistic fixtures, rejects negative quantities and unknown enum values with accurate path strings, blocks oversized arrays exceeding .max(), and refuses malformed JSON syntax cleanly without uncaught SyntaxError crashes. Also include contract regression fixtures captured from staging API logs so that upstream schema changes trigger clear CI diffs before reaching production users.
FAQ
- Why shouldn't I ship an auto-generated Zod schema straight to production?
- Sample JSON inference only observes one snapshot of values. It cannot guess whether status is a closed enum, whether amount must be a positive integer, or whether a null field is normally a string, so human tightening is mandatory.
- What is the difference between .optional(), .nullable(), and .nullish() in Zod?
- .optional() accepts undefined (or a missing JSON key), .nullable() accepts explicit JSON null, and .nullish() accepts both undefined and null. Picking the wrong modifier causes silent rejections on real API traffic.
- How does Zod protect against __proto__ or unexpected extra keys in JSON?
- By default z.object() strips unrecognized keys when parsing, and wrapping schemas with .strict() throws a validation error whenever unknown properties appear. Avoid copying raw JSON objects directly into database updates.
Interactive Tools for This Topic
Report a problem with this articleOpens a pre-filled issue on GitHub.