Zod 4 at the Edges of Your App: Validating Requests, Env Vars, APIs and Webhooks / Nov 24, 2026

8 min readBy Emmanuel Akinfulubi
Zod 4 at the Edges of Your App: Validating Requests, Env Vars, APIs and Webhooks

TypeScript checks your code before it runs. Then the types are erased. When a request body arrives as { "quantity": "lots" }, nothing in your compiled JavaScript knows it was meant to be a number.

That is fine inside your own code, where TypeScript has seen every call. It is not fine at the edges: the places where data comes from somewhere TypeScript has never seen. Request bodies, form posts, environment variables, other companies' APIs, webhooks, URL parameters.

Zod is a schema library that checks data at those edges, at runtime, and gives you the TypeScript type from the same schema. This post shows the pattern for each edge, using Zod 4. Every example was type-checked under strict and run against Zod 4.4.

One schema, one type

import { z } from "zod";
 
const Signup = z.object({
  name: z.string().trim().min(2),
  email: z.email(),
  age: z.number().int().positive().optional(),
});
 
type Signup = z.infer<typeof Signup>;
// { name: string; email: string; age?: number | undefined }

The schema is the source of truth. You never write the Signup type by hand, so the type and the check can't drift apart.

Two defaults are worth knowing. z.object strips unknown keys, so the parsed value only contains what you declared. And .trim() is a transform, so the parsed name comes back trimmed, not just checked.

parse or safeParse

  • parse returns the data or throws. Use it where bad input means the program can't go on, such as configuration at startup.
  • safeParse returns { success: true, data } or { success: false, error }. Use it where bad input is expected and you want to answer it, such as an API route.

Edge 1: request bodies

A Next.js route handler. Two things can go wrong before your logic runs: the body isn't JSON at all, or it is JSON in the wrong shape. Handle both.

// app/api/orders/route.ts
import { z } from "zod";
 
const CreateOrder = z.object({
  productId: z.uuid(),
  quantity: z.number().positive().max(100),
  note: z.string().max(500).optional(),
});
 
export async function POST(request: Request) {
  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return Response.json({ error: "Body must be JSON" }, { status: 400 });
  }
 
  const result = CreateOrder.safeParse(body);
  if (!result.success) {
    return Response.json(
      { error: "Invalid order", fields: z.flattenError(result.error).fieldErrors },
      { status: 400 },
    );
  }
 
  const order = result.data; // fully typed from here on
  // ...create the order
  return Response.json({ ok: true }, { status: 201 });
}

Sending { "productId": "x", "quantity": -1 } returns:

{
  "error": "Invalid order",
  "fields": {
    "productId": ["Invalid UUID"],
    "quantity": ["Too small: expected number to be >0"]
  }
}

Note that quantity is not .int(). On a marketplace that sells fabric by the yard, 1.5 is a real order. Validation should describe your business, not a default.

Validating the shape is not the same as checking permission. A valid order for a product the user can't buy is still valid JSON. Do the authorisation check after the parse, on the server.

Edge 2: environment variables

A missing or malformed variable should stop the app at startup with a clear message, not crash it at 2am when the first email tries to send.

// env.ts
import { z } from "zod";
 
const Env = z.object({
  DATABASE_URL: z.url(),
  RESEND_API_KEY: z.string().min(1),
  PORT: z.coerce.number().int().default(3000),
  MAINTENANCE_MODE: z.stringbool().default(false),
});
 
const parsed = Env.safeParse(process.env);
if (!parsed.success) {
  throw new Error(`Invalid environment:\n${z.prettifyError(parsed.error)}`);
}
 
export const env = parsed.data;

Everything in process.env is a string, so the schema converts as it checks:

  • z.coerce.number() turns "8080" into 8080. "abc" fails instead of becoming NaN.
  • z.stringbool() reads "true", "false", "1", "0", "yes", "no" and similar, which is how people actually write flags.

A bad environment prints something you can act on:

Error: Invalid environment:
✖ Invalid URL
  → at DATABASE_URL
✖ Invalid input: expected string, received undefined
  → at RESEND_API_KEY
✖ Invalid input: expected number, received NaN
  → at PORT

Import env instead of reading process.env around the codebase. Keep this file on the server. In Next.js, only variables starting with NEXT_PUBLIC_ reach the browser, and a server secret should never be one of them.

Edge 3: other people's APIs

Another company's response shape can change without telling you. Validate only the fields you actually use, and let the rest be stripped:

const GitHubUser = z.object({
  login: z.string(),
  name: z.string().nullable(),
  public_repos: z.number(),
});
 
async function getUser(username: string) {
  const res = await fetch(`https://api.github.com/users/${encodeURIComponent(username)}`);
  if (!res.ok) throw new Error(`GitHub returned ${res.status}`);
  return GitHubUser.parse(await res.json());
}

.nullable() matters here. Plenty of real accounts have no display name, and the API sends null, not an empty string. If you guess wrong, you find out from a user, not a test.

When the provider does change something you depend on, you get one clear error at the boundary, not undefined travelling through five functions before something crashes.

Edge 4: webhooks

A webhook endpoint receives several event types on one URL. A discriminated union checks the event field first and then the shape that belongs to it:

const PaystackEvent = z.discriminatedUnion("event", [
  z.object({
    event: z.literal("charge.success"),
    data: z.object({ reference: z.string(), amount: z.number().int() }),
  }),
  z.object({
    event: z.literal("refund.processed"),
    data: z.object({ transaction_reference: z.string() }),
  }),
]);

TypeScript then narrows the type in each branch of a switch (event.event). Events you haven't modelled fail the parse, and you can acknowledge them without acting on them.

The order matters: verify the signature on the raw body first, then parse. A schema proves the shape. Only the signature proves who sent it. I walked through the signature check and the rest of a safe Paystack handler in Accepting Paystack Payments in Next.js Without Losing Money.

Clean data as you check it

Schemas can transform as well as validate. Phone numbers are a good example, because people type them every possible way. This illustrative schema turns any common format of a Nigerian mobile number into one stored form:

const NigerianMobile = z
  .string()
  .transform((raw) => {
    const s = raw.replace(/[\s().-]/g, "");
    if (s.startsWith("+234")) return s;
    if (s.startsWith("234")) return `+${s}`;
    if (s.startsWith("0")) return `+234${s.slice(1)}`;
    return s;
  })
  .pipe(z.string().regex(/^\+234[789]\d{9}$/, { error: "Enter a Nigerian mobile number" }));
 
NigerianMobile.parse("0803 123 4567");   // "+2348031234567"
NigerianMobile.parse("(0803) 123-4567"); // "+2348031234567"
NigerianMobile.parse("2348031234567");   // "+2348031234567"

.pipe() runs a second schema on the transformed value, so the format is checked after it has been cleaned. Store the clean form once, and every search and comparison afterwards is simple.

Rules that span fields

Some checks need two fields at once. .refine() with a path puts the error on the right field, so a form can show it in the right place:

const ChangePassword = z
  .object({ password: z.string().min(8), confirm: z.string() })
  .refine((v) => v.password === v.confirm, {
    error: "Passwords don't match",
    path: ["confirm"],
  });

z.flattenError() on a failed parse gives { confirm: ["Passwords don't match"] }, which maps straight onto a form field.

Coming from Zod 3

If you learned Zod before version 4, these are the changes you'll hit first:

Zod 3Zod 4
z.string().email(), .url(), .uuid()z.email(), z.url(), z.uuid(). The old methods still work but are deprecated
{ message: "..." }{ error: "..." }
err.format() and err.flatten()z.treeifyError(err) and z.flattenError(err), plus z.prettifyError(err) for logs
.strict() and .passthrough()z.strictObject({...}) and z.looseObject({...})
z.lazy() for recursive typesA getter that returns the schema, as below

One behaviour change to watch: z.uuid() is now strict about the version and variant digits. An ID like 11111111-1111-1111-1111-111111111111 fails it. If you only need the 8-4-4-4-12 shape, use z.guid().

Recursive schemas no longer need z.lazy() or a hand-written type:

const Category = z.object({
  name: z.string(),
  get children() {
    return z.array(Category);
  },
});
 
type Category = z.infer<typeof Category>; // recursive, inferred

Where not to use it

Validate at the edges, once. Once data has passed a schema, it is typed. Re-parsing it at every internal function call adds cost and noise without adding safety. For data you produce yourself and never receive from outside, TypeScript alone is enough.

The short version

  • TypeScript's types vanish at runtime. Check data where it enters: requests, env, APIs, webhooks.
  • safeParse where you answer bad input, parse where bad input should stop the program.
  • Let schemas clean data as they check it, and store the clean form.
  • For webhooks, check the signature first. A schema proves the shape, not the sender.

Further reading: the Zod documentation and its Zod 4 changelog.

Frequently asked questions

Why do I need Zod if I already use TypeScript?
TypeScript checks your code before it runs, then its types are erased. Data that arrives at runtime, such as a request body, an environment variable or another company's API response, is never checked by TypeScript. Zod checks it at runtime and gives you the TypeScript type from the same schema.
Should I use parse or safeParse?
Use safeParse where bad input is expected and you want to respond to it, such as an API route returning a 400. Use parse where bad input means the program cannot continue, such as invalid configuration at startup.
What changed in Zod 4?
String formats moved to top-level functions such as z.email(), z.url() and z.uuid(). Custom messages use an error option. Errors are formatted with functions like z.flattenError() and z.prettifyError(). Strict and loose objects have their own constructors, and recursive schemas can use a getter.
Does z.object remove unknown fields?
Yes. By default z.object strips keys it does not know about, so the parsed value only contains what you declared. Use z.strictObject to reject unknown keys, or z.looseObject to keep them.