{"id":13300810,"url":"https://github.com/jkomyno/fastify-zod-validate","last_synced_at":"2026-01-22T20:03:48.478Z","repository":{"id":95192129,"uuid":"515643127","full_name":"jkomyno/fastify-zod-validate","owner":"jkomyno","description":"Fastify route handler validation plugin using Zod in TypeScript","archived":false,"fork":false,"pushed_at":"2022-09-04T10:21:36.000Z","size":57,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2023-03-01T19:51:54.719Z","etag":null,"topics":["fastify","typescript","zod"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jkomyno.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-07-19T15:33:08.000Z","updated_at":"2022-12-26T15:55:40.000Z","dependencies_parsed_at":"2023-04-04T16:21:19.143Z","dependency_job_id":null,"html_url":"https://github.com/jkomyno/fastify-zod-validate","commit_stats":null,"previous_names":[],"tags_count":0,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jkomyno%2Ffastify-zod-validate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jkomyno%2Ffastify-zod-validate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jkomyno%2Ffastify-zod-validate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jkomyno%2Ffastify-zod-validate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jkomyno","download_url":"https://codeload.github.com/jkomyno/fastify-zod-validate/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":242852026,"owners_count":20195757,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastify","typescript","zod"],"created_at":"2024-07-29T17:43:04.666Z","updated_at":"2026-01-22T20:03:48.461Z","avatar_url":"https://github.com/jkomyno.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# fastify-zod-validate\n\n![CI](https://github.com/jkomyno/fastify-zod-validate/workflows/ci/badge.svg?branch=main)\n[![NPM version](https://img.shields.io/npm/v/fastify-zod-validate.svg?style=flat)](https://www.npmjs.com/package/fastify-zod-validate)\n\nA type-safe validation plugin for [Fastify](https://github.com/fastify/fastify) `4.x` and [Zod](https://github.com/colinhacks/zod), arguably the best TypeScript-first validation library.\n\n## Install\n\n```\nnpm i -S fastify-zod-validate\n```\n\n## Features\n\n- Opt-in schema validation for each Fastify route via `fastify.withTypeProvider()`\n- Customize schema validation error when registering the plugin\n\n## Assumptions\n\n- Fastify `4.x` and Zod `3.x` are already installed in your project\n\n## Usage\n\nThe`fastify-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.\nYou can import the plugin using a default import:\n\n```typescript\nimport fastifyZodValidate from 'fastify-zod-validate'\n```\n\n- Define your schemas using `zod`:\n\n```typescript\nimport { z } from 'zod'\n\nexport const UserBody = z.object({\n  username: z.string().min(5).max(10),\n  balance: z.number().min(1000),\n}).strict()\nexport type UserBody = z.infer\u003ctypeof UserBody\u003e\n\nexport const UserPathParams = z.object({\n  userID: z.string().min(4).max(4),\n}).strict()\nexport type UserPathParams = z.infer\u003ctypeof UserPathParams\u003e\n```\n\n- Define your `fastify` router with type-safe schema validation built-in:\n\n```typescript\nimport { FastifyPluginCallback } from 'fastify'\n\nexport const zodValidateRouter: FastifyPluginCallback = (fastify, options, next) =\u003e {\n  fastify.withTypeProvider().route({\n    method: 'POST',\n    url: '/user/:userID',\n    schema: {\n      body: UserBody,\n      params: UserPathParams,\n    },\n    handler: async (request, reply) =\u003e {\n      // no casting or @ts-ignore required\n      const { body, params } = request\n      const { userID } = params\n  \n      await reply.status(200).send({\n        data: {\n          message: `OK user with ID ${userID}`,\n          body,\n        },\n      })\n    }\n  })\n\n  next()\n}\n```\n\n- Register the plugin and setup your `fastify` server:\n\n```typescript\nimport fastifyZodValidate from 'fastify-zod-validate'\nimport Fastify from 'fastify'\n\nexport async function setupServer() {\n  const server = Fastify()\n\n  // register the plugin\n  server.register(fastifyZodValidate, {\n    // optional custom validation error handler\n    handleValidatorError: (error, data) =\u003e {\n      const validationError = new Error('Unprocessable Entity - Custom Zod Validation Error')\n\n      // @ts-ignore\n      validationError.statusCode = 422\n      return { error: validationError }\n    },\n  })\n\n  // register the router\n  server.register(zodValidateRouter, { prefix: 'route' })\n\n  await server.ready()\n  return server\n}\n```\n\n- Start your `fastify` server:\n\n```typescript\nasync function main() {\n  const server = await setupServer()\n  server.listen({ port: 3000 })\n}\n\nmain()\n```\n\n- See validation in action:\n\n  The following HTTP request\n\n  ```bash\n  {\n  curl -0 -X POST http://localhost:3000/route/user/1234 \\\n  -H \"Content-Type: application/json; charset=utf-8\" \\\n  -H \"X-User: user\" \\\n  --data-binary @- \u003c\u003c EOF\n  {\n    \"username\": \"invalid, and checked\",\n    \"balance\": -1\n  }\n  EOF\n  } | jq '.'\n  ```\n\n  will be rejected with the following error\n\n  ```\n  {\n    \"statusCode\": 422,\n    \"error\": \"Unprocessable Entity\",\n    \"message\": \"Unprocessable Entity - Custom Zod Validation Error\"\n  }\n  ```\n\nWe encourage you to take a look at the [`__tests__`](./__tests__) folder for a more complete example.\n\n---------------------------------------------------------\n\n## 🚀 Build and Test package\n\nThis package is built using **TypeScript**, so the source needs to be converted in JavaScript before being usable by the users.\nThis can be achieved by using TypeScript directly:\n\n```sh\nnpm run build\n```\n\nWe run tests via Jest:\n\n```sh\nnpm run test\n```\n\n## 🤝 Contributing\n\nContributions, issues and feature requests are welcome!\u003cbr /\u003eFeel free to check [issues page](https://github.com/jkomyno/fastify-zod-validate/issues).\nThe code is short and tested, so you should feel quite comfortable working on it.\nIf you have any doubt or suggestion, please open an issue.\n\n## ⚠️ Issues\n\nChances are the problem you have bumped into have already been discussed and solved in the past.\nPlease take a look at the issues (both the closed ones and the comments to the open ones) before opening a new issue.\n\n## 🦄 Show your support\n\nGive a ⭐️ if this project helped or inspired you! In the future, I might consider offering premium support to Github Sponsors.\n\n## 👤 Authors\n\n- **Alberto Schiabel**\n  * Github: [@jkomyno](https://github.com/jkomyno)\n  * Twitter: [@jkomyno](https://twitter.com/jkomyno)\n\n## 📝 License\n\nBuilt with ❤️ by [Alberto Schiabel](https://github.com/jkomyno).\u003cbr /\u003e\nThis project is [MIT](https://github.com/jkomyno/fastify-zod-validate/blob/main/LICENSE) licensed.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjkomyno%2Ffastify-zod-validate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjkomyno%2Ffastify-zod-validate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjkomyno%2Ffastify-zod-validate/lists"}