Zod on API Routes Next.js: strict, strip and what actually protects against extra fields
What problem are we solving?
Two attacks that are usually discussed in conjunction with strict validation are:
- Mass assignment. The client sends
{"name":"Ivan","role":"admin"}to the profile update endpoint, and the server doesdb.user.update({ data: body }). Therolefield goes into the database. - Prototype pollution. The body contains the key
__proto__orconstructor.prototype, and the code recursively merges it into an object through a self-writtendeepMerge, changing the prototypeObject.
Both vulnerabilities arise not from the absence of .strict(), but from the fact that the server uses a raw request body. If you validate via Zod and then work only with the result of parse, extra keys will not get there even without strict: by default, z.object discards them (strip mode).
Three object modes
import { z } from "zod";
const Base = { name: z.string().min(1).max(100) };
z.object(Base).parse({ name: "a", role: "admin" });
// { name: "a" } — role молча удалён
z.object(Base).strict().parse({ name: "a", role: "admin" });
// ZodError: unrecognized key "role"
z.object(Base).passthrough().parse({ name: "a", role: "admin" });
// { name: "a", role: "admin" } — опасно для входных данныхIn Zod 4, the same modes are available as separate constructors z.strictObject({...}) and z.looseObject({...}); The .strict() and .passthrough() methods are retained for compatibility. Select one style per project.
Why then strict? It turns a silent deletion into a clear error. A client who misspelled a field name (emial instead of email) receives 400 with the key, rather than a “successful” save without email. For internal APIs and forms, this saves hours of debugging.
Handler template
// app/api/profile/route.ts
import { z } from "zod";
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { db } from "@/lib/db";
const Address = z.strictObject({
city: z.string().max(80),
street: z.string().max(120),
});
const UpdateProfile = z.strictObject({
name: z.string().trim().min(1).max(100).optional(),
email: z.email().optional(), // в Zod 3: z.string().email()
address: Address.optional(),
});
export async function PATCH(req: Request) {
const session = await getSession();
if (!session) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
let json: unknown;
try {
json = await req.json();
} catch {
return NextResponse.json({ error: "invalid JSON" }, { status: 400 });
}
const parsed = UpdateProfile.safeParse(json);
if (!parsed.success) {
return NextResponse.json(
{ error: "validation", issues: parsed.error.issues.map(i => ({ path: i.path, message: i.message })) },
{ status: 400 }
);
}
// только parsed.data, никогда json
const user = await db.user.update({ where: { id: session.userId }, data: parsed.data });
return NextResponse.json({ id: user.id, name: user.name, email: user.email });
}Details that are often missed:
- `strict` is not recursive. A nested
z.objectinside a strict object remains in strip mode. Therefore,Addressis declared separately as strict. - `req.json()` throws exception on invalid JSON. Without
try/catchthe client will receive 500 instead of 400. - `safeParse` instead of `parse` - to avoid catching exceptions for normal user errors.
- The response is also filtered. Return an explicit set of fields, not the entire user object with the password hash.
Query parameters and forms
Everything that comes from searchParams and FormData are strings. Use a cast:
const ListQuery = z.strictObject({
page: z.coerce.number().int().min(1).default(1),
limit: z.coerce.number().int().min(1).max(100).default(20),
q: z.string().max(200).optional(),
});
const query = ListQuery.safeParse(Object.fromEntries(new URL(req.url).searchParams));Object.fromEntries loses duplicate parameters (?tag=a&tag=b). If they are needed, collect the array via searchParams.getAll("tag") separately.
How to diagnose
- A client complains about 400 after the release of a mobile application: the new version sends an additional field, but the scheme is strict. Look at
issuesin the answer - the path to the key will be there. - The field is “not saved”, there are no errors: the scheme is not strict, and the key is called differently than you expect. Temporarily enable
strictand retry the request. - In the logs
__proto__in the keys - the scanner looks for prototype pollution. If you useparsed.data, it's noise; Check to see if there are any raw objects in the merge code.
When strict gets in the way
Webhooks of external services (payment systems, instant messengers) regularly add new fields. A strict scheme on them will turn a harmless provider update into a processing failure. For such inputs, use the strip mode and describe only the necessary fields. The same for public APIs with backward compatibility: a strict scheme on old versions of endpoints can break clients that send fields from new versions.