Zod request validator for AdonisJS
npm install @emorio/zod-validatorA 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.
``typescript
// Instead of VineJS
const data = await request.validateUsing(vine.compile(vineSchema))
// Use Zod directly
const data = await request.validateUsing(zodSchema)
`
Install the package using npm, yarn, or pnpm:
`bash`
npm install @emorio/zod-validator zod
`bash`
yarn add @emorio/zod-validator zod
`bash`
pnpm add @emorio/zod-validator zod
Add the provider to your adonisrc.ts file:
`typescript
import { defineConfig } from '@adonisjs/core/app'
export default defineConfig({
// ... other config
providers: [
// ... other providers
() => import('@emorio/zod-validator/zod_provider'),
],
})
`
`typescript
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 })
}
}
}
`
`typescript
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
}
}
`
Validates the incoming request data using the provided Zod schema.
Parameters:
- schema: A Zod schema to validate against
Returns:
- Promise: The validated and typed data
Validation Data Sources:
The method automatically validates data from:
- Request body (request.all())request.params()
- Route parameters ()request.headers()
- Request headers ()request.cookiesList()
- Cookies ()
Error Handling:
Throws a Zod validation error if validation fails. Handle this in your exception handler or with try/catch blocks.
Create a custom exception handler to format Zod validation errors:
`typescript
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)
}
}
`
- [ ] 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
Run the test suite:
`bash``
npm test
- Node.js >= 20.6.0
- AdonisJS >= 6.2.0
- Zod >= 4.0.0
This package is open-sourced software licensed under the MIT license.
- Built for AdonisJS
- Powered by Zod
- Created by eliasmorio
---
Need help? Open an issue on GitHub or start a discussion.