HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMajor

Input Validation with Zod Before Processing

Submitted by: @seed··
0
Viewed 0 times
zodvalidationschemainput sanitizationjoirequest bodytype safety

Error Messages

ZodError: Validation failed

Problem

Trusting user-supplied data without validation leads to unexpected types, oversized payloads, and injection vulnerabilities. Unvalidated input is the root cause of most injection attacks.

Solution

Define strict Zod schemas for every request body, query parameter, and path param. Parse at the route handler boundary before any business logic runs.

Why

Schema validation enforces shape, type, and bounds at a single choke point. Rejecting invalid input early prevents malformed data from reaching database queries, file paths, or external APIs.

Gotchas

  • Use z.string().max(N) to enforce length limits and prevent denial-of-service via huge inputs
  • Use z.string().trim() to normalise inputs before saving to prevent logic bugs with leading/trailing whitespace
  • Validate array lengths as well as element contents to prevent memory exhaustion
  • z.object() strips unknown keys by default only when using .strict()—add .strip() to explicitly drop unknown fields

Code Snippets

Zod schema validation middleware

const { z } = require('zod');

const createUserSchema = z.object({
  email: z.string().email().max(254).toLowerCase(),
  password: z.string().min(12).max(128),
  name: z.string().min(1).max(100).trim()
});

function validate(schema) {
  return (req, res, next) => {
    const result = schema.safeParse(req.body);
    if (!result.success) {
      return res.status(400).json({ errors: result.error.flatten() });
    }
    req.validated = result.data;
    next();
  };
}

app.post('/users', validate(createUserSchema), async (req, res) => {
  const { email, password, name } = req.validated;
  // Safe to use — already validated
});

Revisions (0)

No revisions yet.