{"_id":"@fastify/type-provider-zod","_rev":"5-89d0c5bef43347b0483b42d7333e971b","name":"@fastify/type-provider-zod","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"@fastify/type-provider-zod","version":"1.0.0","keywords":["fastify","zod","type","provider"],"author":{"name":"turkerd"},"license":"MIT","_id":"@fastify/type-provider-zod@1.0.0","maintainers":[{"name":"simoneb","email":"simone.busoli@gmail.com"},{"name":"delvedor","email":"tommydelved@gmail.com"},{"name":"matteo.collina","email":"hello@matteocollina.com"},{"name":"jsumners","email":"james.sumners@gmail.com"},{"name":"zekth","email":"vince.legoff@gmail.com"},{"name":"eomm","email":"behemoth89@gmail.com"},{"name":"fox1t","email":"maksim@sinik.it"},{"name":"airhorns","email":"harry@harry.me"},{"name":"kibertoad","email":"iselwin@gmail.com"},{"name":"climba03003","email":"kaka@kakawebsitedemo.com"},{"name":"galvez","email":"jonasgalvez@gmail.com"},{"name":"simenb","email":"sbekkhus91@gmail.com"},{"name":"gurgunday","email":"hey@gurgun.day"},{"name":"tony133","email":"a.tripodi133@gmail.com"},{"name":"metcoder95","email":"me@metcoder.dev"},{"name":"jean-michelet","email":"jean.antoine.michelet@gmail.com"}],"homepage":"https://github.com/fastify/fastify-type-provider-zod","bugs":{"url":"https://github.com/fastify/fastify-type-provider-zod/issues"},"tsd":{"directory":"types"},"dist":{"shasum":"59e5daf466b39cd37e4aeaac2684719ed152d215","tarball":"https://registry.npmjs.org/@fastify/type-provider-zod/-/type-provider-zod-1.0.0.tgz","fileCount":45,"integrity":"sha512-X4QIFR0ZMiULemfXItp/FIMSfD0V8qeZ9HkUGyL7HEysuHoMsHyM69OIFhmIICSaZ+l1/V0D3FLNmaKwxQtsMw==","signatures":[{"sig":"MEQCIEvv5qLiETkrVOoyLv0ilr7eVAZDYLQIrEv1TSM3/+4nAiAtdseROEjRTARKW6W6ohXJDACR1WAp/G2AhrStccM5ww==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":124223},"main":"./dist/cjs/index.cjs","type":"module","types":"./dist/cjs/index.d.cts","module":"./dist/esm/index.js","exports":{"default":{"types":"./dist/esm/index.d.ts","default":"./dist/esm/index.js"},"require":{"types":"./dist/cjs/index.d.cts","default":"./dist/cjs/index.cjs"}},"gitHead":"16ad540f0490f7bee150900b67c26fb18c415141","scripts":{"lint":"biome check . && tsc --noEmit","test":"vitest","build":"vite build","prepare":"npm run build","test:ci":"npm run build && npm run typescript && npm run test:coverage","lint:fix":"biome check --write .","typescript":"tsd","test:coverage":"vitest --coverage","prepublishOnly":"npm run build"},"_npmUser":{"name":"gurgunday","email":"hey@gurgun.day"},"repository":{"url":"git+https://github.com/fastify/fastify-type-provider-zod.git","type":"git"},"_npmVersion":"11.11.0","description":"Zod Type Provider for Fastify@5","directories":{},"_nodeVersion":"24.14.1","dependencies":{"@fastify/error":"^4.2.0"},"publishConfig":{"access":"public"},"_hasShrinkwrap":false,"devDependencies":{"tsd":"^0.33.0","zod":"^4.2.0","vitest":"^3.2.4","fastify":"^5.6.1","typescript":"^5.9.3","@types/node":"^24.9.1","oas-validator":"^5.0.8","@biomejs/biome":"^2.3.0","fastify-plugin":"^5.0.1","@fastify/swagger":"^9.5.2","@fastify/swagger-ui":"^5.2.3","@vitest/coverage-v8":"^3.2.4","@readme/openapi-parser":"^5.0.2","unplugin-isolated-decl":"^0.15.2","@kibertoad/biome-config":"^2.0.0"},"peerDependencies":{"zod":">=4.2.0","fastify":"^5.5.0","openapi-types":"^12.1.3","@fastify/swagger":">=9.5.1"},"_npmOperationalInternal":{"tmp":"tmp/type-provider-zod_1.0.0_1776618130794_0.14477484216310765","host":"s3://npm-registry-packages-npm-production"}}},"time":{"created":"2026-04-19T17:02:10.647Z","modified":"2026-08-12T20:02:11.362Z","1.0.0":"2026-04-19T17:02:10.940Z"},"bugs":{"url":"https://github.com/fastify/fastify-type-provider-zod/issues"},"author":{"name":"turkerd"},"license":"MIT","homepage":"https://github.com/fastify/fastify-type-provider-zod","keywords":["fastify","zod","type","provider"],"repository":{"url":"git+https://github.com/fastify/fastify-type-provider-zod.git","type":"git"},"description":"Zod Type Provider for Fastify@5","maintainers":[{"email":"hello@matteocollina.com","name":"matteo.collina"},{"email":"james.sumners@gmail.com","name":"jsumners"},{"email":"behemoth89@gmail.com","name":"eomm"},{"email":"kaka@kakawebsitedemo.com","name":"climba03003"},{"email":"hey@gurgun.day","name":"gurgunday"},{"email":"frazer.dev@icloud.com","name":"fdawgs"},{"email":"ivan@tymoshenko.me","name":"ivan-tymoshenko"}],"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/fastify/fastify-type-provider-zod/actions/workflows/ci.yml/badge.svg)](https://github.com/fastify/fastify-type-provider-zod/actions/workflows/ci.yml)\n\n## Zod compatibility\n\n`@fastify/type-provider-zod` only works with Zod v4.2 or later.\n\n> **Important (v0+)**\n>\n> Starting from **v0**, this library uses Zod’s `.encode()` / `.decode()` APIs introduced in **Zod 4.1**.\n> Because of this change, **response serialization is now based on `z.output<T>` instead of `z.input<T>`**.\n\n## How to use?\n\n```ts\nimport type { ZodTypeProvider } from '@fastify/type-provider-zod';\nimport {\n  serializerCompiler,\n  validatorCompiler,\n} from '@fastify/type-provider-zod';\nimport { z } from 'zod/v4';\n\nconst app = Fastify();\n\n// Add schema validator and serializer\napp.setValidatorCompiler(validatorCompiler);\napp.setSerializerCompiler(serializerCompiler);\n\napp.withTypeProvider<ZodTypeProvider>().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) => {\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```ts\nimport Fastify from 'fastify';\nimport {\n  createSerializerCompiler,\n  validatorCompiler,\n} from '@fastify/type-provider-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/v4';\nimport type { ZodTypeProvider } from '@fastify/type-provider-zod';\nimport {\n  jsonSchemaTransform,\n  createJsonSchemaTransform,\n  serializerCompiler,\n  validatorCompiler,\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(() => {\n  app.withTypeProvider<ZodTypeProvider>().route({\n    method: 'POST',\n    url: '/login',\n    schema: { body: LOGIN_SCHEMA },\n    handler: (req, res) => {\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) => {\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\nWhen provided, this package will automatically create refs using the `jsonSchemaTransformObject` function. You register the schemas with the global Zod registry and assign them an `id`. `fastifySwagger` will then create an OpenAPI document that references the schemas.\n\nThe 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/v4';\nimport type { ZodTypeProvider } from '@fastify/type-provider-zod';\nimport {\n  jsonSchemaTransformObject,\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\nz.globalRegistry.add(USER_SCHEMA, { id: 'User' });\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: jsonSchemaTransformObject,\n});\n\napp.register(fastifySwaggerUI, {\n  routePrefix: '/documentation',\n});\n\napp.after(() => {\n  app.withTypeProvider<ZodTypeProvider>().route({\n    method: 'GET',\n    url: '/users',\n    schema: {\n      response: {\n        200: USER_SCHEMA.array(),\n      },\n    },\n    handler: (req, res) => {\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/v4';\nimport type { 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) => {\n      res.send(req.query.name);\n    },\n  });\n};\n```\n\n## How to specify different OpenAPI targets\n\nYou can specify different JSON Schema targets for OpenAPI compatibility using the `createJsonSchemaTransform` function with the `zodToJsonConfig.target` option.\n\nBy default target 'openapi-3.0' is used for documents with 'openapi' field set to '3.0.x', and target 'draft-2020-12' is used for documents with 'openapi' field set to '3.1.x'.\n\n### Usage\n\n```typescript\nimport { createJsonSchemaTransform } from '@fastify/type-provider-zod';\n\n// For OpenAPI 3.0.x compatibility\nconst transform = createJsonSchemaTransform({\n  zodToJsonConfig: { target: 'openapi-3.0' },\n});\n\n// For OpenAPI 3.1+\nconst transform = createJsonSchemaTransform({\n  zodToJsonConfig: { target: 'draft-2020-12' },\n});\n```\n","readmeFilename":"README.md"}