@emorio/zod-validator
v0.0.4
Published
Zod request validator for AdonisJS
Downloads
2,178
Readme
Zod Validator for AdonisJS
A lightweight, type-safe request validation package for AdonisJS that leverages the power of Zod schemas instead of VineJS.
This package extends AdonisJS's existing validation pattern by adding support for Zod schemas while maintaining the familiar request.validateUsing() API. Instead of learning VineJS syntax, you can use Zod's powerful type-safe validation directly in your AdonisJS controllers.
// Instead of VineJS
const data = await request.validateUsing(vine.compile(vineSchema))
// Use Zod directly
const data = await request.validateUsing(zodSchema)Installation
Install the package using npm, yarn, or pnpm:
npm install @emorio/zod-validator zodyarn add @emorio/zod-validator zodpnpm add @emorio/zod-validator zodConfiguration
1. Register the Provider
Add the provider to your adonisrc.ts file:
import { defineConfig } from '@adonisjs/core/app'
export default defineConfig({
// ... other config
providers: [
// ... other providers
() => import('@emorio/zod-validator/zod_provider'),
],
})Usage
Basic Validation
import { HttpContext } from '@adonisjs/core/http'
import { z } from 'zod'
// Define your Zod schema
const createUserSchema = z.object({
username: z.string().min(3).max(50),
email: z.email(),
age: z.number().int().min(18),
})
export default class UsersController {
async store({ request, response }: HttpContext) {
try {
// Validate request data
const validatedData = await request.validateUsing(createUserSchema)
console.log(validatedData.username) // TypeScript knows this is a string
// Create user with validated data
// ... your logic here
return response.json({ message: 'User created successfully' })
} catch (error) {
return response.status(422).json({ errors: error.errors })
}
}
}Advanced Validation with Headers and Params
import { HttpContext } from '@adonisjs/core/http'
import { z } from 'zod'
export default class PostsController {
async update({ request, response }: HttpContext) {
const updatePostSchema = z.object({
// Request body validation
title: z.string().min(1).max(255),
content: z.string().min(10),
published: z.boolean().optional(),
// Route params validation
params: z.object({
id: z.string().uuid(),
}),
// Headers validation
headers: z.object({
'content-type': z.string(),
'authorization': z.string().startsWith('Bearer '),
}),
// Cookies validation (optional)
cookies: z
.object({
session_id: z.string().optional(),
})
.optional(),
})
const validatedData = await request.validateUsing(updatePostSchema)
// Access validated data with full type safety
const postId = validatedData.params.id
const authToken = validatedData.headers.authorization
const title = validatedData.title
// ... your logic here
}
}API Reference
request.validateUsing<Schema>(schema: Schema): Promise<z.infer<Schema>>
Validates the incoming request data using the provided Zod schema.
Parameters:
schema: A Zod schema to validate against
Returns:
Promise<z.output<Schema>>: The validated and typed data
Validation Data Sources: The method automatically validates data from:
- Request body (
request.all()) - Route parameters (
request.params()) - Request headers (
request.headers()) - Cookies (
request.cookiesList())
Error Handling: Throws a Zod validation error if validation fails. Handle this in your exception handler or with try/catch blocks.
Error Handling
Global Exception Handler
Create a custom exception handler to format Zod validation errors:
import { errors } from '@adonisjs/core'
import { HttpContext } from '@adonisjs/core/http'
import { ZodError } from 'zod'
export default class HttpExceptionHandler extends errors.HttpExceptionHandler {
async handle(error: unknown, ctx: HttpContext) {
if (error instanceof ZodError) {
// z.treeifyError(error);
// handle the error
}
return super.handle(error, ctx)
}
}Roadmap & Enhancements
Planned Features
- [ ] ace add command: Add support for registering by using the node ace add command
- [ ] Tuyau Integration: Generate Tuyau api and types with this zod schema
- [ ] Custom File Validators: Enhanced file validation similar to VineJS file validators
Testing
Run the test suite:
npm testRequirements
- Node.js >= 20.6.0
- AdonisJS >= 6.2.0
- Zod >= 4.0.0
License
This package is open-sourced software licensed under the MIT license.
Credits
- Built for AdonisJS
- Powered by Zod
- Created by eliasmorio
Need help? Open an issue on GitHub or start a discussion.
