Request Validation Pattern (DTO + schema)
On this page
Validation as a Two-Step Process
Production validation is most reliable when you separate parsing from business logic. Step one turns unknown input into typed data. Step two uses that typed data to execute domain rules.
Handler Pattern
- Extract inputs (params, query, body)
- Validate and coerce into typed shape
- Call service with typed inputs
- Format output
Typed Input Example
type CreateUserInput = {
email: string;
name: string;
};
function parseCreateUser(body: unknown): CreateUserInput {
if (!body || typeof body !== 'object') throw new Error('Invalid body');
const b = body as any;
if (typeof b.email !== 'string') throw new Error('Invalid email');
if (typeof b.name !== 'string') throw new Error('Invalid name');
return { email: b.email, name: b.name };
}
Production Guidance
Prefer returning structured validation errors rather than generic messages. Track validation failures in metrics to detect client regressions or abuse patterns.