Skip to the page

Handling requests safely · core

Body parsing and validation with zod

Parse the body with express.json() (with a size limit), then validate params, query and body against a schema such as zod and reject bad input with 400 before it reaches business logic, because anything from the client can be wrong or malicious.

The notes

What you must know

  • express.json() parses application/json bodies (default limit 100kb; bigger bodies get 413). express.urlencoded parses HTML forms; express.raw keeps the exact bytes (needed for webhook signatures).
  • Validate at the edge: body, params and query. The schema can also be your TypeScript type (z.infer<typeof Schema>).
  • zod (v4 current): schema.safeParse(input) returns { success: true, data } or { success: false, error }; z.coerce.number() for query strings; strict objects reject unknown keys.
  • Mass assignment: never pass req.body straight to the database. Pick the allowed fields, or a client can send { "role": "admin" }.
  • Answer 400 (or 422) with field-level errors in one consistent format. Never echo raw input back into HTML.
  • Server validation is required even when the frontend validates. In TypeScript projects share the schema between client and server.
  • Other input attacks: prototype pollution (proto keys merged deeply into objects), NoSQL operator injection ({ "$gt": "" } in Mongo filters), SQL injection (always use parameterised queries).

The red pen

Common traps: mistake → fix

  • Mistake: Frontend validation is enough

    Fix: anyone can call the API directly with curl.

  • Mistake: TypeScript types validate requests

    Fix: types disappear at run time; you need a runtime schema.

  • Mistake: Spread req.body into the update

    Fix: clients can set fields like role or balance (mass assignment).

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you validate request input in an Express API?
  2. Why validate on the server if the form already validates?
  3. How do you keep validation rules and TypeScript types in sync?
  4. What are mass assignment and prototype pollution?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview