Validation
Asena provides built-in validation support using Zod. Validation ensures that incoming request data meets your requirements before reaching your route handlers.
A route declares its validation in one of two ways:
- A route context contract (recommended) - a context subclass built with
Context.define(), taken as the handler's first parameter. Its schemas can come from any Standard Schema v1 library, and the handler reads typed, validated values fromcontext.input. - A validator class - a
ValidationServicesubclass passed as the route'svalidatoroption. Its methods return Zod schemas.
A contract on a route, typed end to end.
02Context.define() and typed context.input.
A ValidationService wired with the validator option.
json(), query(), param() and header validation.
Custom logic that runs after validation.
06The 400 Bad Request shape Asena returns.
07Defining the schemas the validators return.
08The validatorCache route option.
Adapter Support
Both the Ergenecore and the Hono adapter ship validation. Each exports its own ValidationService and ValidationSchemaWithHook, so import them from the adapter you use.
One behavioural difference remains: Ergenecore runs the hook only when validation fails, while the Hono adapter runs it on every validation attempt. Write hooks that check result.success and they behave the same on both.
Installation
Zod is a peer dependency of both adapters — they define the validation contract, they do not ship the library, so your project owns the version:
bun add zodZod v4 or higher is required. Both adapters call flattenError to build the validation-failure envelope, and that is a top-level export introduced in Zod 4.
You may already have it
asena create installs zod for you, and asena generate validator writes import { z } from 'zod' into the file it scaffolds. If you set the project up by hand, add it — before 3.0.0 the import resolved by hoisting out of the adapter's own dependencies, which was never something to rely on.
Why Use Validation?
- Type Safety: Catch type mismatches at runtime
- Security: Prevent malicious or malformed input
- Better Error Messages: Provide clear validation feedback
- Self-Documentation: Schema serves as API documentation
- Automatic Error Handling: 400 Bad Request responses automatically
Quick Start
Define the contract with Context.define() and take it as the handler's first parameter:
import { Controller } from '@asenajs/asena/decorators';
import { Post } from '@asenajs/asena/decorators/http';
import { Context } from '@asenajs/ergenecore';
import { z } from 'zod';
class CreateUserContext extends Context.define({
body: z.object({
name: z.string().min(3).max(50),
email: z.email(),
age: z.number().min(18).max(120),
}),
}) {}
@Controller('/users')
export class UserController {
@Post('/')
async create(context: CreateUserContext) {
const user = context.input.body; // { name: string; email: string; age: number }
return context.send({ created: true, user }, 201);
}
}import { Controller } from '@asenajs/asena/decorators';
import { Post } from '@asenajs/asena/decorators/http';
import { Context } from '@asenajs/hono-adapter';
import { z } from 'zod';
class CreateUserContext extends Context.define({
body: z.object({
name: z.string().min(3).max(50),
email: z.email(),
age: z.number().min(18).max(120),
}),
}) {}
@Controller('/users')
export class UserController {
@Post('/')
async create(context: CreateUserContext) {
const user = context.input.body; // { name: string; email: string; age: number }
return context.send({ created: true, user }, 201);
}
}The request is validated before the handler runs. A body that fails the schema gets a 400 and never reaches create. See Route Context Contracts for every target, the execution order and the error shape.
Validator Classes
A validator class keeps the schemas on a ValidationService component instead of the context. Use it when a route needs validation hooks, schemas built from injected services, or schema factory caching.
1. Create a Validator
Extend ValidationService and implement the json() method:
import { Middleware } from '@asenajs/asena/decorators';
import { ValidationService } from '@asenajs/ergenecore';
import { z } from 'zod';
@Middleware({ validator: true })
export class CreateUserValidator extends ValidationService {
json() {
return z.object({
name: z.string().min(3).max(50),
email: z.string().email(),
age: z.number().min(18).max(120)
});
}
}2. Apply to a Route
Use the validator option in route decorators:
import { Controller } from '@asenajs/asena/decorators';
import { Post } from '@asenajs/asena/decorators/http';
import type { Context } from '@asenajs/ergenecore';
@Controller('/users')
export class UserController {
@Post({ path: '/', validator: CreateUserValidator })
async create(context: Context) {
const body = await context.getBody();
// body is the schema's parsed output, not the raw payload
return context.send({ created: true, user: body }, 201);
}
}Validation Happens Automatically
The validator runs before your route handler. If validation fails, the handler is never called.
What getBody() returns
When a route declares a json validator, context.getBody() returns the schema's output - the value Zod produced, not the JSON the client sent. That means unknown keys are gone, default()s are filled in, and coerce has been applied:
json() {
return z.object({ voteLock: z.boolean() });
}{ "voteLock": true, "ownerId": "<attacker-id>", "password": "plaintext" }await context.getBody(); // { voteLock: true }This matters because z.object() ignores unknown keys rather than rejecting them. Before this behaviour existed, getBody() re-read the raw body and the two extra keys arrived at the handler intact, so the common shape
await this.repository.updateById(id, await context.getBody());was a mass-assignment sink on every validated route - with a schema sitting right next to it that looked like it prevented exactly that.
Body only
Only the body is swapped for its validated form. query, param and header schemas still run, and still reject bad input, but getQuery(), getParam() and headers return the raw request values - a z.coerce.number() on a query parameter validates, then hands you the string. Convert explicitly in the handler for those targets.
Requires hono-adapter 3.1+ / ergenecore 3.1+. On earlier versions getBody() returns the raw body on every route, whatever the schema says.
ValidationService API
The json() Method
The json() method defines the validation schema for request bodies:
@Middleware({ validator: true })
export class MyValidator extends ValidationService {
json() {
// Return a Zod schema
return z.object({
// Your validation rules
});
}
}Method Signature:
json(): ValidationSchema | Promise<ValidationSchema>- Return Type: A Zod schema (
z.ZodType) - Async Support: Can be
asyncfor dynamic schemas
Validating other request parts
json() is the most common, but a validator can define any of these - each takes the same shape (a Zod schema, or { schema, hook }) and validates a different part of the request:
| Method | Validates | Runtime |
|---|---|---|
json() | JSON request body | ✅ |
form() | multipart/form-data / URL-encoded body | ✅ |
query() | Query string | ✅ |
param() | Route parameters | ✅ |
header() | Request headers | ✅ |
response() | Response shape, by status code | ❌ documentation only |
@Middleware({ validator: true })
export class ListUsersValidator extends ValidationService {
public query() {
return z.object({
page: z.string().transform(Number).pipe(z.number().min(1)),
});
}
public param() {
return z.object({ id: z.string().uuid() });
}
}response() is never executed
It exists so @asenajs/asena-openapi can emit response schemas into the spec; the runtime ignores it.
A consequence worth knowing: @Middleware({ validator: true }) requires at least one of the five runtime methods. A validator class that defines only response() fails the decorator's check at import time and the process exits.
Basic Example
@Middleware({ validator: true })
export class ProductValidator extends ValidationService {
json() {
return z.object({
name: z.string(),
price: z.number().positive(),
category: z.enum(['electronics', 'clothing', 'food']),
inStock: z.boolean()
});
}
}Async Validation
For database lookups or async checks:
@Middleware({ validator: true })
export class UniqueEmailValidator extends ValidationService {
@Inject(UserRepository)
private userRepo: UserRepository;
async json() {
return z.object({
email: z.string().email().refine(async (email) => {
const exists = await this.userRepo.findByEmail(email);
return !exists;
}, 'Email already exists')
});
}
}The refine callback runs on every validation, so the lookup sees the current data. The method that returns the schema is a different matter - see the next section.
Schema Factory Caching
json(), query() and the other validator methods are schema factories. How often a route calls them is set by the validatorCache option, available on every HTTP method decorator and on both adapters:
@Post({ path: '/', validator: CreateUserValidator, validatorCache: false })
async create(context: Context) {
return context.send(await context.getBody(), 201);
}validatorCache | When the factory runs | Use it when |
|---|---|---|
true (default) | Once per route and target, while the server starts | The schema is fixed once the application is up |
false | On every request that reaches validation | The factory builds its schema from settings that change after startup or between requests |
With the default, an async factory is awaited during startup, and a factory that throws fails the startup with an error naming the route and the target. @OnStart hooks complete before controller routes are initialized, so state they establish is visible to the factory in either mode.
With false, the validator's methods are still discovered and its injections resolved at startup; only the factory call moves to the request.
What the cache holds is the prepared schema and hook, nothing else:
- Validation itself, and the hook, run on every request.
- No request body, parsed value or response is stored or shared.
- A
refinethat reads mutable state still reads it on each validation. - The cache belongs to one route of one server instance. Two routes using the same validator class, or two applications in one process, each prepare their own.
validatorCache applies to the validator option only. Setting it on a route without a validator, or on a route that uses a context contract, fails startup.
Validation Hooks
Use ValidationSchemaWithHook to execute custom logic after validation:
import { type ValidationSchemaWithHook, ValidationService } from '@asenajs/ergenecore';
@Middleware({ validator: true })
export class UserValidatorWithHook extends ValidationService {
json(): ValidationSchemaWithHook {
return {
schema: z.object({
email: z.string().email(),
password: z.string().min(8)
}),
hook: (result, context) => {
// result: Zod SafeParseResult - { success, data } or { success, error }
// context: Asena's Context wrapper
if (!result.success) {
// Return nothing: the ValidationError is thrown and reaches @Catch
return;
}
console.log('Validated user data:', result.data);
// Store in context for later use
context.setValue('validatedEmail', result.data.email);
}
};
}
}import { type ValidationSchemaWithHook, ValidationService } from '@asenajs/hono-adapter';
@Middleware({ validator: true })
export class UserValidatorWithHook extends ValidationService {
json(): ValidationSchemaWithHook {
return {
schema: z.object({
email: z.string().email(),
password: z.string().min(8)
}),
hook: (result, context) => {
// result: Zod SafeParseResult - { success, data } or { success, error }
// context: Hono's NATIVE context, not Asena's wrapper - see the warning below
if (!result.success) {
// Return nothing: the ValidationError is thrown and reaches @Catch
return;
}
console.log('Validated user data:', result.data);
// Hono's own state API - set()/get(), not setValue()/getValue()
context.set('validatedEmail', result.data.email);
}
};
}
}The hook's context differs per adapter
This is the one place where the two adapters are not interchangeable.
- Ergenecore passes Asena's
Contextwrapper, sosetValue()/getValue()/send()are available. - Hono types the hook as
@hono/zod-validator'sHook, which hands you Hono's native context. Useset()/get()to store state andjson()to respond.
The values you store are still readable from the handler's Asena context - setValue and Hono's set write to the same per-request store.
Hook Function Signature
hook: (
result: z.ZodSafeParseResult<T>,
context: Context
) => Response | void | Promise<Response | void>| Parameter | Type | Description |
|---|---|---|
result | z.ZodSafeParseResult<T> | Zod's safe-parse result: { success: true, data } or { success: false, error } |
context | Context | The adapter's Context object |
| Returns | Response | void | Return a Response to answer the request yourself; return nothing to continue |
The hook receives the parse result, not the parsed data
result is not the validated object - the data lives at result.data, and only when result.success is true. Always branch on result.success first.
The return value is not a way to transform the payload. Returning a plain object does nothing; only a Response is honoured, and it short-circuits the request.
Hook Use Cases
1. Logging and Monitoring
hook: (result, context) => {
console.log('Validation attempted:', {
endpoint: context.req.url,
ok: result.success
});
}Returning nothing leaves the error contract untouched - a failure is still reported the normal way.
2. Storing Validated Data in Context
hook: (result, context) => {
if (!result.success) return;
// Make validated data available to middlewares/handlers
context.setValue('validatedUser', result.data);
context.setValue('userEmail', result.data.email);
}3. Answering the Request Yourself
hook: (result, context) => {
if (result.success) return;
// A Response short-circuits everything - the handler never runs and
// no @Catch is consulted for this request
return context.send({ error: 'Invalid signup payload' }, 422);
}4. Side Effects
hook: async (result, context) => {
if (!result.success) return;
// Send notification, update cache, etc.
await this.notificationService.sendAlert('New signup', result.data.email);
}Validation Error Responses
When validation fails, Asena answers with 400 Bad Request.
Default response
A ValidationError is always thrown. When nothing answers it - no @Catch matches it, or the one that matches returns nothing - both adapters fall back to the same envelope, Zod's flattened error:
{
"error": "Validation failed",
"details": {
"formErrors": [],
"fieldErrors": {
"email": ["Invalid email"],
"age": ["Must be at least 18"]
}
},
"target": "json"
}target names the part of the request that failed - json, query, form, param or header.
The failure is also logged like any other 4xx, at DEBUG (or INFO when your logger has no debug). See Error Handling.
Customizing the response
A @Catch in an @ExceptionHandler receives validation failures like any other error, so they can share your application's response envelope:
import { ExceptionHandler } from '@asenajs/asena/decorators';
import { Catch, type ExceptionContext } from '@asenajs/asena/exception';
import { ContractValidationError, type ValidationErrorLike } from '@asenajs/asena/adapter';
import { ValidationError, type Context } from '@asenajs/hono-adapter';
@ExceptionHandler()
export class ValidationExceptionHandler {
@Catch(ValidationError, ContractValidationError)
public validation(error: ValidationErrorLike, ctx: ExceptionContext<Context>) {
if (ctx.scope !== 'http') return;
return ctx.context.send(
{
success: false,
message: 'Validation failed',
errors: error.issues // [{ path, message, code }]
},
400
);
}
}ValidationError comes from your adapter package and is what a validator class throws; ContractValidationError comes from @asenajs/asena/adapter and is what a route context contract throws. Both carry target, issues and cause (the original ZodError for a validator class) and satisfy isValidationError().
A generic HTTP handler still answers 400
Both errors are HTTP exceptions carrying status 400. Without a narrower @Catch, a @Catch(HttpException) receives them and answers from error.status, so validation failures never silently become 500s. A @Catch(ValidationError) is more specific and wins for its own type.
A hook that returns a Response wins
If the validator's hook returns a Response, that response is sent as-is and no @Catch is consulted for that request. See Validation Hooks.
Route Context Contracts
A route context contract puts a route's request schemas on a context class. The handler takes that class as its first parameter, and Asena validates the request against it before the handler runs. The same schemas drive the validated values, their TypeScript types and the OpenAPI request schemas.
Defining a Contract
Context is exported by both adapters as a type and a value. Context.define() takes a schema map and returns a context class to extend:
import { Controller } from '@asenajs/asena/decorators';
import { Post } from '@asenajs/asena/decorators/http';
import { Context } from '@asenajs/ergenecore';
import { z } from 'zod';
class CreateUserContext extends Context.define({
body: z.object({ name: z.string().trim(), age: z.coerce.number().default(18) }),
query: z.object({ notify: z.stringbool().default(false) }),
}) {
get displayName() {
return this.input.body.name.toUpperCase();
}
}
@Controller('/users')
export class UserController {
@Post('/')
async create(context: CreateUserContext) {
const user = await context.getBody(); // { name: string; age: number }
return context.send({ name: context.displayName, notify: context.input.query.notify, user }, 201);
}
}import { Controller } from '@asenajs/asena/decorators';
import { Post } from '@asenajs/asena/decorators/http';
import { Context } from '@asenajs/hono-adapter';
import { z } from 'zod';
class CreateOrderContext extends Context.define({
body: z.object({ quantity: z.coerce.number().int().positive() }),
params: z.object({ shopId: z.coerce.number() }),
}) {}
@Controller('/shops')
export class OrderController {
@Post('/:shopId/orders')
async create(context: CreateOrderContext) {
const { shopId } = context.input.params; // number
const { quantity } = await context.getBody(); // number
return context.send({ shopId, quantity }, 201);
}
}The handler receives a real instance of your subclass, so instanceof and getters you add to it work. A class built by one adapter's Context.define() cannot be used on the other adapter; the route fails at startup naming both.
Targets
| Key | Validates | Value passed to the schema |
|---|---|---|
body | JSON request body | The parsed JSON; undefined when the body is empty |
form | multipart/form-data or URL-encoded body | An object; a repeated field becomes an array |
query | Query string | An object; a repeated key becomes an array, a single one stays a string |
params | Route parameters | An object of strings |
headers | Request headers | An object with lowercase header names |
Each schema must implement Standard Schema v1. Zod is one such library; any other implementation works the same way, and both synchronous and async validation are supported. Asena does not depend on a schema library for contracts.
Context.define() rejects a key outside this list, a value that is not a Standard Schema, and a map that declares both body and form. A misspelled target is already a compile error:
class CreateUserContext extends Context.define({
bdoyObject literal may only specify known properties, and 'bdoy'
does not exist in type 'ExactRequestSchemas<…>'.
ts(2353): z.object({ name: z.string() }),
}) {}
Targets are validated in the order body/form, query, params, headers. Validation stops at the first target that fails.
What the Handler Sees
context.input holds the schema output for each declared target, with defaults, transforms and coercions applied. Only declared targets exist on it - context.input.params on a contract without params is a compile error.
Hover the highlighted names to see what each schema produces:
class OrderContext extends Context.define({
params: z.object({ id: z.coerce.number().int() }),
query: z.object({
since: z.iso.date().transform((s) => new Date(s)),
tags: z.string().transform((s) => s.split(',')).optional(),
}),
headers: z.object({ 'x-tenant': z.enum(['eu', 'us']) }),
}) {}
@Controller('/orders')
export class OrderController {
@Get('/:id')
async find(context: OrderContext) {
const { idconst id: number } = context.input.params(property) params: {
id: number;
}
const sinceconst since: Date = context.input.query.since
const tagsconst tags: string[] | undefined = context.input.query.tags
const tenantconst tenant: "eu" | "us" = context.input.headers['x-tenant']
}
}
| Accessor | Returns |
|---|---|
context.input.<target> | The validated output of that target |
getBody() | The validated body output, typed without a generic |
getParseBody() | The validated form output, typed without a generic |
getQuery(), getParam(), headers | The raw request values |
input is ready synchronously when the handler runs, and each request gets its own. The map is read-only and frozen at the top level; the schemas and the output objects inside it are not deep-frozen.
input throws when read before route validation has finished - in a middleware, in the class constructor, or in a field initializer. A getter on the subclass is fine, as long as it is read from the handler.
Execution Order
global middleware → controller middleware → auth guard → route middleware → contract validation → handlerThe auth guard exists only on routes marked @Protected / @Roles, when @asenajs/asena-auth is imported. It answers before validation, so an anonymous client sending an invalid body gets a 401, not a 400.
This order is the same on both adapters. A middleware that reads the body does not consume it: validation still receives the full body. When validation fails or a middleware answers the request itself, the handler does not run.
Errors
| Situation | Status |
|---|---|
| A schema reports issues | 400 |
Malformed JSON in a body request | 400 |
A non-empty body request whose content type is not application/json or application/*+json | 415 |
A form request whose content type is not multipart/form-data or application/x-www-form-urlencoded | 415 |
A failing schema throws a ContractValidationError from @asenajs/asena/adapter, which isValidationError() recognizes and a @Catch can match by type. Its target is the contract key (body, form, query, params, headers) and its issues carry path and message, with each path segment normalized to a string or a number. Without a @Catch that answers it, the response is:
{
"error": "Validation failed",
"target": "body",
"issues": [{ "message": "Too small: expected number to be >0", "path": ["quantity"] }]
}An exception thrown from inside a schema is not a validation failure. It reaches @Catch as it was thrown.
A route cannot combine a contract with the validator option. Doing so, or setting validatorCache on a contract route, fails startup.
Requirements
Asena finds the contract from the TypeScript metadata of the handler's first parameter. That needs:
experimentalDecoratorsandemitDecoratorMetadataenabled intsconfig.json- the context class referenced as a value - declared in the same file, or imported without
import type
When the metadata is missing, the route is registered without a contract: nothing is validated and reading context.input throws. A class that TypeScript erased to a type cannot be recovered at runtime.
Integration with Controllers
Route-Level Validation
@Controller('/products')
export class ProductController {
@Post({ path: '/', validator: CreateProductValidator })
async create(context: Context) {
// Body is already validated
const product = await context.getBody();
return context.send(product, 201);
}
@Put({ path: '/:id', validator: UpdateProductValidator })
async update(context: Context) {
const id = context.getParam('id');
const updates = await context.getBody();
return context.send({ updated: true });
}
}Combining with Middleware
@Protected()
@Post({
path: '/',
middlewares: [RateLimitMiddleware],
validator: CreateUserValidator
})
async create(context: Context) {
// auth guard -> RateLimitMiddleware -> CreateUserValidator -> handler
}Both adapters run the guard and the route's middleware chain first and validate after them, so the session the guard resolved, and anything a middleware stored with context.setValue(), are on the context when the validator reads the request. Global and controller middleware run before all of them.
Zod Schema Definition
Asena uses Zod for schema definition. The json() method returns a Zod schema:
json() {
return z.object({
name: z.string(),
email: z.string().email(),
age: z.number().int().positive()
});
}Reusable Schemas
You can extract and reuse common schemas across multiple validators:
// src/validators/schemas/common.ts
import { z } from 'zod';
// Reusable schema definitions
export const emailSchema = z.string().email().toLowerCase();
export const passwordSchema = z.string().min(8).regex(/[A-Z]/).regex(/[0-9]/);
export const addressSchema = z.object({
street: z.string().min(1),
city: z.string().min(1),
zipCode: z.string().regex(/^\d{5}$/),
country: z.string().length(2)
});
export const paginationSchema = z.object({
page: z.number().int().positive().default(1),
limit: z.number().int().min(1).max(100).default(10)
});Then use them in your validators:
import { Middleware } from '@asenajs/asena/decorators';
import { ValidationService } from '@asenajs/ergenecore';
import { emailSchema, passwordSchema, addressSchema } from '../schemas/common';
import { z } from 'zod';
@Middleware({ validator: true })
export class CreateUserValidator extends ValidationService {
json() {
return z.object({
email: emailSchema, // Reuse common schema
password: passwordSchema, // Reuse common schema
shippingAddress: addressSchema // Reuse common schema
});
}
}
@Middleware({ validator: true })
export class UpdateUserValidator extends ValidationService {
json() {
return z.object({
email: emailSchema.optional(), // Reuse and modify
shippingAddress: addressSchema.partial() // All fields optional
});
}
}Benefits of Reusable Schemas
- Consistency: Same validation rules across your app
- Maintainability: Update once, apply everywhere
- Type Safety: Share types between validators
- Composition: Build complex schemas from simple ones
Zod API Documentation
For complete schema documentation including strings, numbers, arrays, objects, unions, transformations, and refinements, see the Zod API Documentation.
Asena-Specific Best Practices
1. Use Validators for All User Input
// ✅ Good: Validate all POST/PUT/PATCH requests
@Post({ path: '/', validator: CreateUserValidator })
async create(context: Context) { }2. Keep Validators Focused
// ✅ Good: One validator per endpoint
@Middleware({ validator: true })
export class CreateUserValidator extends ValidationService {
json() {
return z.object({
name: z.string(),
email: z.string().email()
});
}
}3. Use Hooks for Context Integration
// ✅ Good: Use hooks to enrich context
hook: (result, context) => {
context.setValue('userId', result.id);
context.setValue('userRole', result.role);
}4. Leverage Dependency Injection
// ✅ Good: Inject services in validators
@Middleware({ validator: true })
export class UniqueUsernameValidator extends ValidationService {
@Inject(UserService)
private userService: UserService;
async json() {
return z.object({
username: z.string().refine(async (name) => {
return !(await this.userService.usernameExists(name));
}, 'Username already taken')
});
}
}ValidationSchema Types
// Simple schema
type ValidationSchema = z.ZodType<any, z.ZodTypeDef, any>;
// Schema with hook
interface ValidationSchemaWithHook {
schema: ValidationSchema;
hook?: (result: any, context: Context) => any;
}Complete Example
Here's a real-world validator with hooks and service injection:
import { Middleware } from '@asenajs/asena/decorators';
import { ValidationService, type ValidationSchemaWithHook } from '@asenajs/ergenecore';
import { Inject } from '@asenajs/asena/decorators/ioc';
import { z } from 'zod';
@Middleware({ validator: true })
export class RegisterUserValidator extends ValidationService {
@Inject(UserService)
private userService: UserService;
@Inject(Logger)
private logger: Logger;
async json(): Promise<ValidationSchemaWithHook> {
return {
schema: z.object({
username: z.string()
.min(3, 'Username must be at least 3 characters')
.max(20)
.regex(/^[a-zA-Z0-9_]+$/, 'Alphanumeric and underscore only')
.refine(async (name) => {
const exists = await this.userService.usernameExists(name);
return !exists;
}, 'Username already taken'),
email: z.string()
.email('Invalid email')
.transform(v => v.toLowerCase()),
password: z.string()
.min(8, 'Password must be at least 8 characters')
.regex(/[A-Z]/, 'Must contain uppercase letter')
.regex(/[0-9]/, 'Must contain number'),
confirmPassword: z.string(),
terms: z.literal(true, {
errorMap: () => ({ message: 'Must accept terms' })
})
}).refine((data) => data.password === data.confirmPassword, {
message: 'Passwords do not match',
path: ['confirmPassword']
}),
// The hook receives Zod's SafeParseResult - the data lives at `result.data`
// and only when `result.success` is true
hook: (result, context) => {
if (!result.success) {
// Returning a Response overrides the adapter's default 400 envelope
return context.send({ success: false, issues: result.error.issues }, 400);
}
this.logger.info('User registration validated', {
username: result.data.username,
email: result.data.email
});
// Stash the parsed data for the handler to pick up with context.getValue()
const { confirmPassword, ...userData } = result.data;
context.setValue('registrationData', userData);
}
};
}
}The hook cannot transform the payload
The return value is a Response override, not a transformed body. Returning a plain object is silently ignored - the handler still receives the original parsed data. To pass a reshaped value along, write it to the context with setValue() as above.
Note also that Ergenecore invokes the hook only on failure, while Hono invokes it on every attempt. Guard on result.success so the same hook works under both adapters.
Related
- Controllers - Using validators in controllers
- Middleware - Understanding middleware flow
- Context API - Working with Context in hooks
- Configuration - Global error and validation setup
- Ergenecore Adapter - Ergenecore-specific features
- Zod Documentation - Complete Zod schema guide