Validation & error handling

Zod schemas at the boundary, typed errors, mapping failures to 4xx vs 5xx. Never trust the client — server-side validation is the trust boundary.

About 26 min read3-question knowledge check

The mental model

Your API is a country and every incoming request is a traveller at the border. Validation is passport control: it checks documents at the point of entry, once, against a published set of rules — and everything inside the country can then assume travellers are legitimate. Error handling is the consular service: when something goes wrong, the traveller gets a clear, translated explanation of what was wrong and what to do next, while the country's internal police reports (stack traces, SQL fragments) stay internal.

What breaks without it: the client is a hostile input device. Not because your users are attackers (some are), but because clients drift — an old mobile build sends amount as a string, a partner's webhook adds a field, a browser extension mangles a payload, a QA engineer pastes an emoji into a numeric field. Without a boundary check, that garbage travels: it becomes NaN in a calculation, undefined in a template literal, a null in a NOT NULL column, and finally a 500 error four layers away from the actual cause — or worse, a silently wrong row in the database that nobody notices for weeks.

The one idea that explains most of the topic: validate at the trust boundary, then never again. Parse the untyped outside world into typed, verified data exactly once, at the edge. Inside the boundary, the type system carries the guarantee. Re-validating in every internal function is noise; validating nowhere is negligence. The slogan worth quoting in interviews: *parse, don't validate* — the output of validation should be a new, narrower type, not a boolean next to the same untrusted value.

The full lesson continues with 15 more sections
  • Deep dive
  • Internal architecture
  • Real-world use cases
  • Best practices
  • Common mistakes
  • Performance
  • Security
  • Production troubleshooting
  • Advantages & disadvantages
  • Alternatives
  • Interview expectations
  • Interview questions
  • Facts to remember
  • Cheat sheet
  • Quick revision