Server-Side Validation and Errors
Never trust the client, fail loudly inside, speak clearly outside - and log the whole story.
Before this: Relational Data Modeling
Objective
Harden the API boundary: whitelist-validate everything arriving over HTTP, return uniform error envelopes, handle failures deliberately, and log enough to diagnose tomorrow's bug today.
Vocabulary
The words to use when directing your agent.
- payload
- The data carried inside a request or response body.
- whitelist validation
- Accepting only known-good values and shapes, rejecting everything else by default.
- error envelope
- One consistent JSON shape every error response uses.
- log level
- Severity tag on a log line - info, warn, error - enabling filtering later.
- stack trace
- The chain of function calls leading to an error - gold for diagnosis.
Understand it
Bypassing the browser in ten seconds
Open a terminal, POST invalid JSON straight at the API. Whatever frontend validation existed is now irrelevant. This single exercise - doing it deliberately - permanently installs the never-trust-client reflex.
Logs are tomorrow's memory
Three weeks from now, someone will ask why orders failed at 3am. The answer will exist only if today's code logged request identity, action and outcome - WITHOUT passwords, tokens or personal payloads. Logging secrets converts your log file into a liability.
Core concepts
The client is an adversary's playground
Anything delivered to the browser can be modified, replayed or skipped entirely. curl needs no form and respects no rules. Server-side checks are not redundancy - they are the only checks that exist.
Fail loud inside, speak calm outside
Internally, errors deserve full stack traces and noisy logs. Externally, clients get disciplined envelopes: what happened, in their vocabulary, minus internal details like file paths and queries. Leaked internals are reconnaissance gifts.
Examples
The uniform envelope
Every failure answers { "error": { "code": "VALIDATION", "message": "amount must be positive" } }. Clients learn ONE parsing rule for ALL failures. Consistency here is API kindness.
Good line versus bad line
Good: WARN POST /expenses 400 ip=1.2.3.4 reason=amount_negative. Bad: logging the full payload including someone's password field. Same event; one is diagnosable, the other is a breach.
Common mistakes
Common mistake
Empty catch blocks swallowing errors into silence.
Fix
Every caught error gets logged with context and produces a deliberate response - silence is never acceptable.
Common mistake
Validating only the happy shape (present and non-empty) while ignoring type absurdities.
Fix
Whitelist-check types and bounds too: amount must be a NUMBER, not a string claiming to be one.
Working with your AI agent
Commission an adversarial suite: ask your agent to generate fifteen hostile requests - wrong types, giant strings, nested objects where scalars belong, duplicated fields, unicode abuse - and implement handling for each BEFORE looking at its code. Reviewing a defense plan beats reviewing defensive code line by line.
Build it
The module’s real project. Your agent builds; you direct and inspect.
Project: Trust Nothing
Harden the Expense API into a paranoid, professional boundary: whitelist validation on every input, uniform error envelope everywhere, deliberate failure handling, and honest logs that leak nothing.
Requirements
- Every endpoint validates method, content type, payload shape, field types and bounds via shared whitelist rules
- All error responses use the single documented envelope shape
- Unhandled exceptions produce 500 envelope + logged stack trace without crashing the server
- Request logging captures method, path, status and duration - never passwords or payload contents
- An adversarial request suite (10+ hostile requests) lives in the repo with expected outcomes documented
Context for your agent
Harden my Expense API. Centralize whitelist validation so every route validates through one layer; adopt the error envelope everywhere including 404s and unhandled exceptions; add request logging that records method/path/status/duration but explicitly redacts bodies; write the adversarial suite as a runnable script with expected-vs-actual outcomes. Show me the validation rule table before implementing. The server must survive every attack without restarting.
Verify it - twice
Check every item yourself first. Then hand your agent the prompt and compare verdicts.
Verification prompt - paste into your AI agent
Red-team my Trust Nothing hardening. Run the adversarial suite yourself, then go beyond it. Verify PASS or FAIL with evidence: (1) every hostile input met the expected status and envelope, (2) no response leaked stacks, paths, queries or schema details, (3) logs contain zero password/payload material, (4) an induced unhandled exception produced 500-plus-trace-log without downtime, (5) validation truly centralizes in one layer. Then invent five attacks my suite missed, run them, and honestly report which ones drew blood.
Run this against “Server-Side Validation and Errors” after your own checklist pass. Where the agent and you disagree, investigate before moving on.
Review questions
Answer out loud. If you cannot, revisit before moving on.
Demonstrate bypassing your own frontend validation with curl.
Which three fields must EVERY log line carry, and which class of data must none carry?
Why is one error envelope shape a security property, not just tidiness?
You can now
- Treat every inbound byte as hostile and validate accordingly
- Design error contracts clients can rely on
- Log forensically useful information without creating liabilities
Up next
Authentication