jkomyno/fastify-zod-validate(opens in a new tab)
Language: TypeScript
Fastify route handler validation plugin using Zod in TypeScript
- stars
- 7
- watchers
- 1
- forks
- 0
- open issues
- 1
- Last updated
- 09/04/2022
Language: TypeScript
Fastify route handler validation plugin using Zod in TypeScript
A type-safe validation plugin for Fastify 4.x and Zod, arguably the best TypeScript-first validation library.
npm i -S fastify-zod-validate
fastify.withTypeProvider()4.x and Zod 3.x are already installed in your projectThefastify-zod-validate plugin decorates the fastify instance with a withTypeProvider function, which can be used to compile and validate the fastify schemas (comprising HTTP body, path parameters, query parameters, headers and more) using the zod library.
You can import the plugin using a default import:
import fastifyZodValidate from 'fastify-zod-validate'
zod:import { z } from 'zod' export const UserBody = z.object({ username: z.string().min(5).max(10), balance: z.number().min(1000), }).strict() export type UserBody = z.infer<typeof UserBody> export const UserPathParams = z.object({ userID: z.string().min(4).max(4), }).strict() export type UserPathParams = z.infer<typeof UserPathParams>
fastify router with type-safe schema validation built-in:import { FastifyPluginCallback } from 'fastify' export const zodValidateRouter: FastifyPluginCallback = (fastify, options, next) => { fastify.withTypeProvider().route({ method: 'POST', url: '/user/:userID', schema: { body: UserBody, params: UserPathParams, }, handler: async (request, reply) => { // no casting or @ts-ignore required const { body, params } = request const { userID } = params await reply.status(200).send({ data: { message: `OK user with ID ${userID}`, body, }, }) } }) next() }
fastify server:import fastifyZodValidate from 'fastify-zod-validate' import Fastify from 'fastify' export async function setupServer() { const server = Fastify() // register the plugin server.register(fastifyZodValidate, { // optional custom validation error handler handleValidatorError: (error, data) => { const validationError = new Error('Unprocessable Entity - Custom Zod Validation Error') // @ts-ignore validationError.statusCode = 422 return { error: validationError } }, }) // register the router server.register(zodValidateRouter, { prefix: 'route' }) await server.ready() return server }
fastify server:async function main() { const server = await setupServer() server.listen({ port: 3000 }) } main()
See validation in action:
The following HTTP request
{
curl -0 -X POST http://localhost:3000/route/user/1234 \
-H "Content-Type: application/json; charset=utf-8" \
-H "X-User: user" \
--data-binary @- << EOF
{
"username": "invalid, and checked",
"balance": -1
}
EOF
} | jq '.'will be rejected with the following error
{
"statusCode": 422,
"error": "Unprocessable Entity",
"message": "Unprocessable Entity - Custom Zod Validation Error"
}
We encourage you to take a look at the __tests__ folder for a more complete example.
This package is built using TypeScript, so the source needs to be converted in JavaScript before being usable by the users. This can be achieved by using TypeScript directly:
npm run build
We run tests via Jest:
npm run testContributions, issues and feature requests are welcome!
Feel free to check issues page.
The code is short and tested, so you should feel quite comfortable working on it.
If you have any doubt or suggestion, please open an issue.
Chances are the problem you have bumped into have already been discussed and solved in the past. Please take a look at the issues (both the closed ones and the comments to the open ones) before opening a new issue.
Give a ⭐️ if this project helped or inspired you! In the future, I might consider offering premium support to Github Sponsors.
Built with ❤️ by Alberto Schiabel.
This project is MIT licensed.