Sub topic 15
Validating API bodies, environment variables, and forms
Earlier chapters covered schemas, parse and safeParse, refinements, transforms, and coercion. This chapter puts them together at the three places where untrusted data enters most applications. It assumes you can write a Zod object schema, call safeParse, and read error.issues.
What counts as a boundary
A boundary is any point where data enters your program from something you do not control. TypeScript trusts the annotations you write. A value typed CreateUser that came from request.json() is only a claim, because json() returns any.
The three common boundaries differ in what they deliver:
| Boundary | Raw shape | Typical problems |
|---|---|---|
| JSON API body | Parsed JSON, or unparseable text | Missing fields, wrong types, extra keys |
| Environment variables | Strings or `undefined` only | Numbers and booleans arrive as text, values missing |
| HTML forms | `FormData` with string or `File` values | Empty strings for blank inputs, checkboxes absent when unchecked |
The pattern is the same at all three. Convert the raw input to unknown, run it through a schema once, and let only the validated result into the rest of the code.
Validating a JSON API body
Two things can go wrong with a body. The text may not be JSON at all, and the JSON may have the wrong shape. Handle them separately so the client gets a useful message for each. This handler uses the standard Request and Response classes, which exist in Node 18 and later.
import { z } from "zod";
const CreateUser = z.object({
name: z.string().min(1),
age: z.number().int().min(0),
role: z.enum(["admin", "member"]).default("member"),
});
type CreateUser = z.infer<typeof CreateUser>;
export async function handleCreateUser(request: Request): Promise<Response> {
let json: unknown;
try {
json = await request.json();
} catch {
return Response.json({ error: "Body is not valid JSON" }, { status: 400 });
}
const result = CreateUser.safeParse(json);
if (!result.success) {
return Response.json(
{
error: "Invalid body",
issues: result.error.issues.map((issue) => ({
path: issue.path.join("."),
message: issue.message,
})),
},
{ status: 400 },
);
}
const user: CreateUser = result.data;
return Response.json({ created: user }, { status: 201 });
}Several choices here are deliberate:
jsonis typedunknown, so the compiler forces you to validate before using it.- The handler uses
safeParse. A bad body is an expected event, so it is handled as a return value instead of an exception. - The response lists
pathandmessagefor every issue, so a client can show all problems at once. - By default
z.objectstrips unknown keys from the output. If a client sending extra fields should be an error, use.strict(). If you need to pass them through, use.passthrough()(renamed.loose()in Zod 4).
Use result.data, not the original json. Defaults, stripped keys, and transforms are only applied in the output.
Query strings and route parameters
Query strings and path parameters are also strings. Validate them with a schema of their own and use z.coerce for numbers.
const ListQuery = z.object({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
});
const query = ListQuery.parse(Object.fromEntries(new URL("https://x.test/users?page=2").searchParams));
// { page: 2, limit: 20 }Validating environment variables
Environment variables have the strictest limits. Every value is a string or undefined, and a missing one often breaks the program far from where it was read. The fix is to validate all of them once, at startup, and fail immediately with a readable message.
import { z } from "zod";
const Env = z.object({
NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
DATABASE_URL: z.string().min(1),
DEBUG: z
.enum(["true", "false"])
.default("false")
.transform((value) => value === "true"),
});
function loadEnv() {
const result = Env.safeParse(process.env);
if (!result.success) {
for (const issue of result.error.issues) {
console.error(`Invalid environment variable ${issue.path.join(".")}: ${issue.message}`);
}
process.exit(1);
}
return result.data;
}
export const env = loadEnv();
// env.PORT is a number, env.DEBUG is a booleanExport env and import it everywhere instead of reading process.env directly. Then code elsewhere in the program gets typed values and no longer needs its own Number(process.env.PORT) conversions.
z.coerce.number() has a similar trap. It calls Number(), so an empty string becomes 0 and passes. For a required port, PORT= set to an empty value would silently become 0 in the schema above, but .min(1) rejects it. The range check is what protects you here, so keep it.
Validating forms
FormData adds two problems of its own.
- A blank text input is submitted as an empty string, not as a missing field.
z.string().optional()accepts"", andz.coerce.number()turns it into0. - An unchecked checkbox is not submitted at all, and a checked one sends
"on"unless you set avalue.
Normalize the form to a plain object first, dropping empty strings, then let the schema describe the rules.
import { z } from "zod";
function formToObject(formData: FormData): Record<string, unknown> {
const out: Record<string, unknown> = {};
for (const [key, value] of formData.entries()) {
if (value === "") continue;
out[key] = value;
}
return out;
}
const Signup = z
.object({
email: z.string().min(3),
age: z.coerce.number().int().min(13),
password: z.string().min(8),
confirm: z.string(),
newsletter: z
.string()
.optional()
.transform((value) => value === "on"),
})
.refine((data) => data.password === data.confirm, {
message: "Passwords do not match",
path: ["confirm"],
});
const form = new FormData();
form.set("email", "[email protected]");
form.set("age", "36");
form.set("password", "correct horse");
form.set("confirm", "correct horse");
form.set("newsletter", "on");
const result = Signup.safeParse(formToObject(form));
if (result.success) {
console.log(result.data.age + 1, result.data.newsletter); // 37 true
}After the empty strings are dropped, a blank age is reported as a missing or invalid number instead of passing as 0.
Two details affect error display. The path: ["confirm"] option puts the mismatch message on the confirm field, where a form UI can show it. Also, a refinement on an object does not run if the object's fields already failed, so a user with an invalid email sees that error first, and the password mismatch appears after they fix it.
To show errors next to inputs, group issues by field:
function fieldErrors(error: z.ZodError): Record<string, string[]> {
const grouped: Record<string, string[]> = {};
for (const issue of error.issues) {
const key = issue.path.join(".") || "_form";
(grouped[key] ??= []).push(issue.message);
}
return grouped;
}Zod also provides error.flatten() (in Zod 4, z.flattenError). The helper above works in both major versions and makes the path handling explicit.
Choosing what to do on failure
The right reaction depends on the boundary:
| Boundary | On failure | Reason |
|---|---|---|
| API body | Return 400 with issue paths | The client can fix its request |
| Environment | Log every issue and exit | The program cannot run correctly |
| Form | Return field errors to the page | The user can correct the input |
| Data from your own trusted service | `parse` and let it throw | A mismatch is a bug, not user error |
Common mistakes
- Annotating
const body: CreateUser = await request.json(). This compiles but checks nothing. - Reading from the original input after parsing instead of
result.data. - Using
parsein a request handler without atry/catch, so one bad body becomes a 500 response. - Using
z.coerce.boolean()for text flags. - Validating deep inside business logic instead of once at the edge, which repeats work and leaves some paths unchecked.
Exercise
A form has an optional "age" field. Users who leave it blank should pass validation, and users who enter a value must give an integer of at least 13. With z.coerce.number().int().min(13).optional(), a blank field is submitted as "". What happens, and how do you fix it?
Show answer
"" is not undefined, so optional() does not apply. Coercion turns "" into 0, which then fails min(13), so a blank field is wrongly rejected. Fix it by dropping empty strings before parsing, as formToObject does, so the field is missing and optional() accepts it. The schema then stays z.coerce.number().int().min(13).optional().
Exercise
Your server reads process.env.ENABLE_CACHE and a teammate wrote z.coerce.boolean().default(false) for it. A deployment sets ENABLE_CACHE=false, yet caching turns on. Why, and what schema fixes it?
Show answer
Boolean("false") is true, because any non-empty string is truthy. Use z.enum(["true", "false"]).default("false").transform((value) => value === "true"), which accepts only the two expected strings and produces a real boolean.