Skip to content

Validation System

DomusJS integrates Zod as the default schema validation library, making it easy to validate inputs, DTOs, and command/query payloads.

✅ Zod provides a fluent, type-safe way to define and check data shapes.
✅ DomusJS also includes built-in Express middleware to automatically validate incoming requests from params, body, or query.
✅ You can swap in any other validation library if needed.


  • Fully TypeScript-native: great type inference.
  • Simple API for defining schemas.
  • Built-in support for nested objects, refinements, and transformations.
  • Easy to plug into the request pipeline.

import { z } from 'zod';
export const RegisterUserSchema = z.object({
username: z.string().min(3),
email: z.string().email(),
password: z.string().min(8),
});
import { RegisterUserSchema } from './schemas/register-user.schema';
const result = RegisterUserSchema.safeParse(input);
if (!result.success) {
throw new BadRequestError('Invalid input', 'VALIDATION_ERROR');
}
const { username, email, password } = result.data;
// proceed with the valid data

✅ This ensures inputs are validated before reaching the domain layer.


DomusJS provides prebuilt middleware to validate incoming request parts automatically.

import { validateBody, validateQuery, validateParams } from '@domusjs/infrastructure';
import { RegisterUserSchema } from './schemas/register-user.schema';
app.post('/auth/register', validateBody(RegisterUserSchema), (req, res) => {
// At this point, req.body is already validated
const data = req.body;
// Implment the registration logic here
});

validateBody(schema) → validates req.body
validateQuery(schema) → validates req.query
validateParams(schema) → validates req.params

If validation fails, the middleware throws a BadRequestError automatically.


DomusJS does not enforce Zod — you can integrate your own validator by following the same middleware pattern.

✅ Always validate external inputs before entering the domain layer.
✅ Use schemas for commands, queries, DTOs, and external API data.
✅ Keep validation and domain rules separate — they serve different purposes.
✅ For reusable validators, create a dedicated validators/ directory or module.