Zod 22 🛡️ Server-Side Validation — Why client-side Zod alone is insufficient for security
A Zod schema running in the browser is a user-experience tool, not a security control. The browser is the attacker’s environment: they can disable JavaScript, open DevTools, modify the request payload, or bypass the form entirely with curl or a bot . The schema that validated the form never runs. The server receives whatever bytes the attacker chose to send, and if the server trusts the client’s validation, it trusts the attacker.
This chapter covers why client-side Zod is bypassable, the trust boundary rule that determines where validation must run, and the shared-schema pattern that keeps the rules identical on both sides without duplicating them. The sections that follow walk through the bypass mechanisms, the server-side validation patterns for API routes and Server Actions, and the defense-in-depth rule that Zod is the input layer, not the whole stack.
Key point: Client-side validation is a convenience for the user; server-side validation is the security control. The same Zod schema should run on both, but the server must never assume the client ran it, and the server must safeParse the raw input before any handler logic touches it.
Why client-side Zod is bypassable
The disabled-JavaScript problem. OWASP’s guidance is explicit: “any JavaScript input validation performed on the client can be bypassed by an attacker that disables JavaScript or uses a Web Proxy” . A form that relies on Zod in the browser for its only validation is a form that accepts invalid data when the browser does not cooperate. The server sees the submission regardless.
The DevTools problem. The browser is not a trusted execution environment. An attacker can modify the form’s action URL, change the input values after validation, remove the required attribute, or call the API endpoint directly with a crafted payload. The schema that ran in the browser validated the attacker’s first values, not the ones that arrived at the server .
The shared-schema illusion problem. A common anti-pattern is to define a Zod schema, use it with zodResolver in the browser, and assume the server is protected because “the schema is shared.” The schema is shared; the execution is not. The server must call safeParse on the raw request body, not trust that the client’s handleSubmit ran the resolver .
a. The trust boundary rule
Validation belongs at the boundary where data crosses from an untrusted source into the application. Zod’s security value is entirely about where it is applied: a schema defined and never called protects nothing .
The boundaries that require server-side Zod validation are:
| Boundary | Why | Pattern |
|---|---|---|
| HTTP request body | Attacker controls bytes | schema.safeParse(req.body) |
| Query strings and route params | Attacker controls URL | schema.safeParse(req.query) |
| Server Actions (Next.js) | Client can invoke directly | schema.safeParse(formData) |
| Message queue payloads | Producer may be compromised | schema.safeParse(JSON.parse(msg)) |
| External API responses | Partner may send malformed data | schema.safeParse(await res.json()) |
| Environment variables | Deploy config may be wrong | schema.parse(process.env) |
The rule is mechanical: if the data came from outside the process, it is untrusted, and it must be parsed before any handler logic reads a property. Validating deep in business logic allows corrupt data to propagate and makes debugging harder .
b. Server-side patterns for API routes and Server Actions
The pattern differs by framework, but the structure is the same: safeParse the raw input, return a 400 on failure, and pass the parsed data to the handler.
Next.js API route:
import { z } from "zod";
import { NextRequest, NextResponse } from "next/server";
const Schema = z.object({
email: z.email(),
age: z.number().int().positive(),
});
export async function POST(req: NextRequest) {
const body = await req.json(); // untrusted
const result = Schema.safeParse(body);
if (!result.success) {
return NextResponse.json({ issues: result.error.issues }, { status: 400 });
}
// result.data is typed and validated
return NextResponse.json(await createUser(result.data));
}
The safeParse call is the gate. If it fails, the handler returns before touching result.data, and the attacker’s payload never reaches the database or the business logic.
React 19 Server Action:
'use server';
import { contactSchema } from '@/schemas/contact';
export async function submitContact(formData: FormData) {
const result = contactSchema.safeParse({
name: formData.get('name'),
email: formData.get('email'),
message: formData.get('message'),
});
if (!result.success) {
return { errors: z.treeifyError(result.error).properties };
}
await saveContact(result.data);
return { success: true };
}
The Server Action receives FormData, not a typed object. The safeParse call converts the raw form entries into the schema’s output type, or returns the error tree that the client maps back to fields with setError . The handler’s saveContact call receives result.data, which TypeScript knows is the validated type.
c. Zod is the input layer, not the whole stack
Validating structure does not make data safe to use. Zod enforces that a field is a string of a certain length, a number in a range, an enum member. It does not encode output, parameterize queries, or check authorization .
| Threat | Zod’s role | Still required |
|---|---|---|
| XSS | Validates string length and format | Context-aware output encoding |
| SQL injection | Validates identifier format | Parameterized queries |
| Mass assignment | .strictObject() rejects unknown keys | Explicit field binding |
| Broken access control | None | Authorization checks |
The z.strictObject() pattern is the one Zod-specific defense that matters for mass assignment. A default z.object() strips unknown keys, which means an attacker who sends {"email": "...", "isAdmin": true} has the isAdmin key silently dropped. That is safe by default, but z.strictObject() rejects the request entirely, which surfaces the tampering . The choice depends on whether the API should tolerate extra fields from clients or treat them as an error.
Complete Example Session
// ============================================
// PART 1: THE SHARED SCHEMA
// ============================================
import { z } from "zod";
export const SignupSchema = z.strictObject({
email: z.email(),
password: z.string().min(8),
role: z.enum(["user", "admin"]).default("user"),
});
export type Signup = z.infer<typeof SignupSchema>;
// ============================================
// PART 2: THE CLIENT (CONVENIENCE)
// ============================================
// zodResolver(SignupSchema) validates in the browser
// This improves UX. It is NOT the security control.
// ============================================
// PART 3: THE SERVER (SECURITY CONTROL)
// ============================================
export async function POST(req: Request) {
const body = await req.json();
const result = SignupSchema.safeParse(body);
if (!result.success) {
return new Response(JSON.stringify({ issues: result.error.issues }), {
status: 400,
});
}
// result.data is validated and typed
// The attacker cannot reach this line with invalid data
return new Response(JSON.stringify(await createUser(result.data)), {
status: 201,
});
}
// ============================================
// PART 4: THE DEFENSE-IN-DEPTH CHECKLIST
// ============================================
// - Zod at the boundary: done
// - Output encoding: still required
// - Parameterized queries: still required
// - Authorization: still required
// - Rate limiting: still required
// - CSRF token: still required
The parts covered the shared schema, the client’s convenience role, the server’s security gate, and the defense-in-depth checklist.
Quick Reference
Bypass Mechanisms
| Mechanism | What the attacker does | Zod’s protection |
|---|---|---|
| Disable JavaScript | Submits form without client validation | None |
| DevTools | Modifies values after validation | None |
| Direct API call | Skips the form entirely | None |
| Proxy | Intercepts and modifies the request | None |
Server-Side Patterns
| Framework | Raw Input | Parse Pattern |
|---|---|---|
| Next.js API | await req.json() | Schema.safeParse(body) |
| Server Action | FormData | Schema.safeParse({ field: formData.get(...) }) |
| Express | req.body | Schema.safeParse(req.body) |
| tRPC | Procedure input | .input(Schema) |
Zod’s Limits
| Zod does | Zod does not |
|---|---|
| Validate structure | Encode output |
| Enforce length/format | Parameterize queries |
| Reject unknown keys (strict) | Check authorization |
| Infer types | Rate limit |
Best Practices
✅ Do This:
// safeParse on the server
const result = Schema.safeParse(body); // ✅
// Return 400 before handler logic
if (!result.success) return json(result.error.issues, 400); // ✅
// Use the parsed data, not the raw body
await createUser(result.data); // ✅
// Use strictObject for mass-assignment protection
z.strictObject({ ... }); // ✅
❌ Don’t Do This:
// Trust the client's validation
const user = createUser(body); // body is unknown // ❌
// Use parse in a handler without try/catch
const data = Schema.parse(body); // throws 500 // ❌
// Assume zodResolver on the client is security
// The server never ran it // ❌
// Validate deep in business logic
function processOrder(data: unknown) { Schema.parse(data); } // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Invalid data reaches database | No server-side parse | safeParse at the boundary |
| 500 on invalid input | .parse() used in handler | .safeParse() and return 400 |
| Mass assignment | Unknown keys silently stripped | z.strictObject() |
| Client validation “works” but server crashes | Server never parsed | Shared schema, server execution |
| Error shape broken after v4 upgrade | error.errors removed | Use z.treeifyError() |
Real-World Examples
1. Server Action with safeParse
const result = contactSchema.safeParse({ name: formData.get('name') });
2. API route with 400
if (!result.success) return json(result.error.issues, 400);
3. Strict object for mass assignment
z.strictObject({ email: z.email(), role: z.enum(["user"]) });
4. tRPC input validator
publicProcedure.input(z.object({ name: z.string() }))
5. Environment validation
EnvSchema.parse(process.env);
6. External API response validation
const users = UsersSchema.parse(await res.json());
7. Message queue payload
const msg = MessageSchema.safeParse(JSON.parse(raw));
8. Error mapping to client
return { errors: z.treeifyError(result.error).properties };
9. Client setError mapping
setError('email', { message: state.errors.email.errors[0] });
10. Defense-in-depth note
Zod validates; encoding, queries, and authz are separate controls.
Visual
The Trust Boundary
┌─────────────────────────────────────────────────────────┐
│ UNTRUSTED TRUSTED │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ Browser │ │ Server │ │
│ │ Form, DevTools, │ │ Handler, DB │ │
│ │ curl, proxy │ │ │ │
│ └──────────────────┘ └──────────────────┘ │
│ │ ▲ │
│ │ attacker controls │ │
│ ▼ │ │
│ ┌──────────────────────────────────────────┐ │
│ │ Zod safeParse (THE GATE) │ │
│ └──────────────────────────────────────────┘ │
│ │
│ Client Zod = UX. Server Zod = security. │
└─────────────────────────────────────────────────────────┘
The Shared-Schema Pattern
┌─────────────────────────────────────────────────────────┐
│ schemas/user.ts │
│ export const UserSchema = z.strictObject({ ... }); │
│ │ │
│ ├──► Client: zodResolver(UserSchema) │
│ │ └── instant feedback, not security │
│ │ │
│ └──► Server: UserSchema.safeParse(body) │
│ └── security gate, 400 on failure │
│ │
│ One schema, two executions. The server never trusts │
│ that the client ran it. │
└─────────────────────────────────────────────────────────┘
Zod’s Role in Defense-in-Depth
┌─────────────────────────────────────────────────────────┐
│ LAYER 1: INPUT VALIDATION (Zod) │
│ structure, length, format, enum membership │
│ │ │
│ ▼ │
│ LAYER 2: OUTPUT ENCODING │
│ context-aware escaping for HTML, SQL, etc. │
│ │ │
│ ▼ │
│ LAYER 3: PARAMETERIZED QUERIES │
│ never string concatenation for SQL │
│ │ │
│ ▼ │
│ LAYER 4: AUTHORIZATION │
│ valid ID does not mean the caller may access it │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Client validation | UX only; bypassable |
| Server validation | Security control; mandatory |
| Server method | safeParse on raw input |
| Failure response | 400 with issues, not 500 |
| Mass assignment | z.strictObject() |
| Shared schema | Same rules, two executions |
| Zod’s limits | Not output encoding, not authz |
| v4 error shape | z.treeifyError() replaces .flatten() |
Key takeaways:
- Client-side Zod is a convenience, not a control. The browser can disable JavaScript, modify values, or skip the form entirely. The server must parse the raw input regardless of what the client claims to have validated .
- The server uses
safeParse, notparse. A failed parse returns a 400 with the issues array; a thrown error becomes a 500 that reveals nothing useful and confuses the client. The handler returns before touching the data . - The schema is shared, but the execution is not. One file defines the rules; the client uses
zodResolverfor feedback, the server callssafeParsefor the gate. The server never assumes the client ran the resolver . z.strictObject()closes mass assignment. A default object strips unknown keys silently; strict rejects the request, surfacing tampering attempts .- Zod is the input layer. Output encoding, parameterized queries, and authorization are separate controls that Zod does not replace. A valid string can still be an XSS payload if it is rendered without encoding .
Remember: The schema that runs in the browser is a courtesy to the user. The schema that runs on the server is the security boundary. They can be the same file, but they are never the same execution. If the server does not call safeParse on the raw input, the validation did not happen, no matter what the client did.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!