{"id":13767268,"url":"https://github.com/turkerdev/fastify-type-provider-zod","last_synced_at":"2025-05-14T13:05:50.717Z","repository":{"id":39365069,"uuid":"473279039","full_name":"turkerdev/fastify-type-provider-zod","owner":"turkerdev","description":null,"archived":false,"fork":false,"pushed_at":"2025-04-14T15:41:57.000Z","size":155,"stargazers_count":470,"open_issues_count":57,"forks_count":25,"subscribers_count":7,"default_branch":"main","last_synced_at":"2025-05-13T16:14:24.104Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/turkerdev.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":"CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2022-03-23T16:53:49.000Z","updated_at":"2025-05-12T16:56:53.000Z","dependencies_parsed_at":"2024-02-15T10:27:47.165Z","dependency_job_id":"600124c2-dec8-4ff0-a559-c24128bc5b48","html_url":"https://github.com/turkerdev/fastify-type-provider-zod","commit_stats":{"total_commits":71,"total_committers":11,"mean_commits":6.454545454545454,"dds":0.5915492957746479,"last_synced_commit":"63bc5a3e9ea52dd1c26c3b34d39eb182c08ee6ee"},"previous_names":[],"tags_count":5,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/turkerdev%2Ffastify-type-provider-zod","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/turkerdev%2Ffastify-type-provider-zod/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/turkerdev%2Ffastify-type-provider-zod/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/turkerdev%2Ffastify-type-provider-zod/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/turkerdev","download_url":"https://codeload.github.com/turkerdev/fastify-type-provider-zod/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254098572,"owners_count":22014514,"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":[],"created_at":"2024-08-03T16:01:06.843Z","updated_at":"2025-05-14T13:05:50.689Z","avatar_url":"https://github.com/turkerdev.png","language":"TypeScript","funding_links":[],"categories":["TypeScript","APIs and Servers"],"sub_categories":[],"readme":"# Fastify Type Provider Zod\n\n[![NPM Version](https://img.shields.io/npm/v/fastify-type-provider-zod.svg)](https://npmjs.org/package/fastify-type-provider-zod)\n[![NPM Downloads](https://img.shields.io/npm/dm/fastify-type-provider-zod.svg)](https://npmjs.org/package/fastify-type-provider-zod)\n[![Build Status](https://github.com//turkerdev/fastify-type-provider-zod/workflows/CI/badge.svg)](https://github.com//turkerdev/fastify-type-provider-zod/actions)\n\n## How to use?\n\n```js\nimport Fastify from \"fastify\";\nimport { serializerCompiler, validatorCompiler, ZodTypeProvider } from \"fastify-type-provider-zod\";\nimport z from \"zod\";\n\nconst app = Fastify()\n\n// Add schema validator and serializer\napp.setValidatorCompiler(validatorCompiler);\napp.setSerializerCompiler(serializerCompiler);\n\napp.withTypeProvider\u003cZodTypeProvider\u003e().route({\n  method: \"GET\",\n  url: \"/\",\n  // Define your schema\n  schema: {\n    querystring: z.object({\n      name: z.string().min(4),\n    }),\n    response: {\n      200: z.string(),\n    },\n  },\n  handler: (req, res) =\u003e {\n    res.send(req.query.name);\n  },\n});\n\napp.listen({ port: 4949 });\n```\n\nYou can also pass options to the `serializerCompiler` function:\n\n```ts\ntype ZodSerializerCompilerOptions = {\n  replacer?: ReplacerFunction;\n};\n```\n\n```js\nimport Fastify from 'fastify';\nimport { createSerializerCompiler, validatorCompiler } from 'fastify-type-provider-zod';\nimport z from 'zod';\n\nconst app = Fastify();\n\nconst replacer = function (key, value) {\n  if (this[key] instanceof Date) {\n    return { _date: value.toISOString() };\n  }\n  return value;\n};\n\n// Create a custom serializer compiler\nconst customSerializerCompiler = createSerializerCompiler({ replacer });\n\n// Add schema validator and serializer\napp.setValidatorCompiler(validatorCompiler);\napp.setSerializerCompiler(customSerializerCompiler);\n\n// ...\n\napp.listen({ port: 4949 });\n```\n\n## How to use together with @fastify/swagger\n\n```ts\nimport fastify from 'fastify';\nimport fastifySwagger from '@fastify/swagger';\nimport fastifySwaggerUI from '@fastify/swagger-ui';\nimport { z } from 'zod';\n\nimport {\n  jsonSchemaTransform,\n  createJsonSchemaTransform,\n  serializerCompiler,\n  validatorCompiler,\n  ZodTypeProvider,\n} from 'fastify-type-provider-zod';\n\nconst app = fastify();\napp.setValidatorCompiler(validatorCompiler);\napp.setSerializerCompiler(serializerCompiler);\n\napp.register(fastifySwagger, {\n  openapi: {\n    info: {\n      title: 'SampleApi',\n      description: 'Sample backend service',\n      version: '1.0.0',\n    },\n    servers: [],\n  },\n  transform: jsonSchemaTransform,\n\n  // You can also create transform with custom skiplist of endpoints that should not be included in the specification:\n  //\n  // transform: createJsonSchemaTransform({\n  //   skipList: [ '/documentation/static/*' ]\n  // })\n});\n\napp.register(fastifySwaggerUI, {\n  routePrefix: '/documentation',\n});\n\nconst LOGIN_SCHEMA = z.object({\n  username: z.string().max(32).describe('Some description for username'),\n  password: z.string().max(32),\n});\n\napp.after(() =\u003e {\n  app.withTypeProvider\u003cZodTypeProvider\u003e().route({\n    method: 'POST',\n    url: '/login',\n    schema: { body: LOGIN_SCHEMA },\n    handler: (req, res) =\u003e {\n      res.send('ok');\n    },\n  });\n});\n\nasync function run() {\n  await app.ready();\n\n  await app.listen({\n    port: 4949,\n  });\n\n  console.log(`Documentation running at http://localhost:4949/documentation`);\n}\n\nrun();\n```\n\n## Customizing error responses\n\nYou can add custom handling of request and response validation errors to your fastify error handler like this:\n\n```ts\nimport { hasZodFastifySchemaValidationErrors } from 'fastify-type-provider-zod'\n\nfastifyApp.setErrorHandler((err, req, reply) =\u003e {\n    if (hasZodFastifySchemaValidationErrors(err)) {\n        return reply.code(400).send({\n            error: 'Response Validation Error',\n            message: \"Request doesn't match the schema\",\n            statusCode: 400,\n            details: {\n                issues: err.validation,\n                method: req.method,\n                url: req.url,\n            },\n        })\n    }\n\n    if (isResponseSerializationError(err)) {\n        return reply.code(500).send({\n            error: 'Internal Server Error',\n            message: \"Response doesn't match the schema\",\n            statusCode: 500,\n            details: {\n                issues: err.cause.issues,\n                method: err.method,\n                url: err.url,\n            },\n        })\n    }\n    \n    // the rest of the error handler\n})\n```\n\n## How to create refs to the schemas?\n\nIt is possible to create refs to the schemas by using the `createJsonSchemaTransformObject` function. You provide the schemas as an object and fastifySwagger will create a OpenAPI document in which the schemas are referenced. The following example creates a ref to the `User` schema and will include the `User` schema in the OpenAPI document.\n\n```ts\nimport fastifySwagger from '@fastify/swagger';\nimport fastifySwaggerUI from '@fastify/swagger-ui';\nimport fastify from 'fastify';\nimport { z } from 'zod';\nimport type { ZodTypeProvider } from 'fastify-type-provider-zod';\nimport {\n  createJsonSchemaTransformObject,\n  jsonSchemaTransform,\n  serializerCompiler,\n  validatorCompiler,\n} from 'fastify-type-provider-zod';\n\nconst USER_SCHEMA = z.object({\n  id: z.number().int().positive(),\n  name: z.string().describe('The name of the user'),\n});\n\nconst app = fastify();\napp.setValidatorCompiler(validatorCompiler);\napp.setSerializerCompiler(serializerCompiler);\n\napp.register(fastifySwagger, {\n  openapi: {\n    info: {\n      title: 'SampleApi',\n      description: 'Sample backend service',\n      version: '1.0.0',\n    },\n    servers: [],\n  },\n  transform: jsonSchemaTransform,\n  transformObject: createJsonSchemaTransformObject({\n    schemas: {\n      User: USER_SCHEMA,\n    },\n  }),\n});\n\napp.register(fastifySwaggerUI, {\n  routePrefix: '/documentation',\n});\n\napp.after(() =\u003e {\n  app.withTypeProvider\u003cZodTypeProvider\u003e().route({\n    method: 'GET',\n    url: '/users',\n    schema: {\n      response: {\n        200: USER_SCHEMA.array(),\n      },\n    },\n    handler: (req, res) =\u003e {\n      res.send([]);\n    },\n  });\n});\n\nasync function run() {\n  await app.ready();\n\n  await app.listen({\n    port: 4949,\n  });\n\n  console.log(`Documentation running at http://localhost:4949/documentation`);\n}\n\nrun();\n```\n\n## How to create a plugin?\n\n```ts\nimport { z } from 'zod';\nimport { FastifyPluginAsyncZod } from 'fastify-type-provider-zod';\n\nconst plugin: FastifyPluginAsyncZod = async function (fastify, _opts) {\n  fastify.route({\n    method: 'GET',\n    url: '/',\n    // Define your schema\n    schema: {\n      querystring: z.object({\n        name: z.string().min(4),\n      }),\n      response: {\n        200: z.string(),\n      },\n    },\n    handler: (req, res) =\u003e {\n      res.send(req.query.name);\n    },\n  });\n};\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fturkerdev%2Ffastify-type-provider-zod","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fturkerdev%2Ffastify-type-provider-zod","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fturkerdev%2Ffastify-type-provider-zod/lists"}