Sub topic 15
Validating API Bodies, Environment Variables, and Forms
Assume you know basic TypeScript types, JavaScript objects and JSON, npm imports, and try/catch. This chapter focuses on where untrusted data enters an application. A type annotation describes what your code expects, but it does not check data at runtime. A Zod schema performs that check.
Validate API request bodies
An API request body is data sent by a client. The client might send missing fields, extra fields, or values with the wrong type. Validate the body before passing it to application logic.
import { z } from "zod";
const CreateUser = z.object({
name: z.string().trim().min(1),
age: z.number().int().min(13),
email: z.string().email(),
});
type CreateUser = z.infer<typeof CreateUser>;
function handleCreateUser(body: unknown) {
const result = CreateUser.safeParse(body);
if (!result.success) {
return {
status: 400,
body: {
error: "Invalid request",
issues: result.error.issues,
},
};
}
const user: CreateUser = result.data;
return {
status: 201,
body: { message: `Created ${user.email}` },
};
}
const response = handleCreateUser({
name: "Mina",
age: 25,
email: "[email protected]",
});
console.log(response);Use unknown for data that came from outside the program. This prevents your code from using the value before validation. After safeParse succeeds, result.data has the inferred, validated type.
Validate environment variables
Environment variables are always strings or absent. Convert them while validating them.
import { z } from "zod";
const Environment = z.object({
PORT: z.coerce.number().int().min(1).max(65535).default(3000),
DEBUG: z
.enum(["true", "false"])
.default("false")
.transform((value) => value === "true"),
DATABASE_URL: z.string().url(),
});
const config = Environment.parse(process.env);
console.log(config.PORT); // number
console.log(config.DEBUG); // boolean
console.log(config.DATABASE_URL); // stringz.coerce.number() converts a string such as "8080" into 8080. default supplies a value when the variable is missing. parse throws when configuration is invalid, which is often appropriate during startup because the application should not run with a broken configuration.
Validate form data
HTML form controls commonly submit strings. Checkboxes may submit "on", and a missing checkbox may be undefined. Create a schema that matches the actual submitted representation.
import { z } from "zod";
const ProfileForm = z.object({
displayName: z.string().trim().min(2, "Use at least 2 characters"),
age: z.coerce.number().int().min(13),
receiveNews: z
.union([z.literal("on"), z.undefined()])
.transform((value) => value === "on"),
});
const formInput: unknown = {
displayName: " Lee ",
age: "21",
receiveNews: "on",
};
const parsed = ProfileForm.safeParse(formInput);
if (parsed.success) {
console.log(parsed.data);
// { displayName: "Lee", age: 21, receiveNews: true }
}Keep boundary schemas separate when representations differ. An API may send a JSON number, while a form sends the same value as a string. Both can produce the same internal type after parsing.
Choose the right boundary behavior
| Boundary | Common input representation | Useful Zod approach |
|---|---|---|
| API body | JSON object | `safeParse` and return a client error |
| Environment | Strings or missing values | `parse`, coercion, and defaults |
| Form | Strings and missing controls | Coercion, unions, and transformations |
A schema is most valuable at the boundary. Once data has passed validation, internal functions can rely on the parsed result instead of repeating checks throughout the application.
Exercise
Why should an API handler validate an incoming body before assigning it to a TypeScript type?
Show answer
TypeScript types disappear at runtime, so validation is required to check that the actual external value has the expected shape.