Node.js theorytheory 0/50 · 0%
Safety · medium

27. Validating input

Never trust data from the network.

Every value coming from a request body, query string or header is untrusted and must be validated before use — wrong types, missing fields and malicious payloads are all normal, expected input from the internet, not edge cases.

js
function validateTransferRequest(body) {
  const errors = [];
  if (typeof body.to !== "string" || !/^0x[0-9a-fA-F]{40}$/.test(body.to)) {
    errors.push("to must be a valid address");
  }
  if (typeof body.amount !== "string" || !/^\d+$/.test(body.amount)) {
    errors.push("amount must be a numeric string");
  }
  return errors;
}

app.post("/transfer", (req, res) => {
  const errors = validateTransferRequest(req.body);
  if (errors.length) return res.status(400).json({ errors });
  // safe to proceed
});

Libraries like Zod or Joi turn this hand-written pattern into declarative schemas, but the underlying principle is the same: validate at the boundary, before any business logic runs.

Check your understanding

  1. 1. Why must request bodies be validated even from a trusted-looking client?

  2. 2. Where should validation happen relative to business logic?

  3. 3. What do libraries like Zod add over hand-written validation?