Create schema references (refs) for OpenAPI
mainTo avoid duplicating schemas in your OpenAPI document and instead use $ref, register your schemas with the global Zod registry using z.globalRegistry.add(schema, { id: 'Name' }). Then, configure @fastify/swagger with both transform: jsonSchemaTransform and transformObject: jsonSchemaTransformObject.
import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUI from '@fastify/swagger-ui';
import fastify from 'fastify';
import { z } from 'zod/v4';
import type { ZodTypeProvider } from 'fastify-type-provider-zod';
import {
jsonSchemaTransformObject,
jsonSchemaTransform,
serializerCompiler,
validatorCompiler,
} from 'fastify-type-provider-zod';
const USER_SCHEMA = z.object({
id: z.number().int().positive(),
name: z.string().describe('The name of the user'),
});
// Register schema with a global ID for referencing
z.globalRegistry.add(USER_SCHEMA, { id: 'User' });
const app = fastify();
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(serializerCompiler);
app.register(fastifySwagger, {
openapi: {
info: { title: 'SampleApi', version: '1.0.0' },
servers: [],
},
transform: jsonSchemaTransform,
transformObject: jsonSchemaTransformObject,
});
app.register(fastifySwaggerUI, { routePrefix: '/documentation' });
app.after(() => {
app.withTypeProvider<ZodTypeProvider>().route({
method: 'GET',
url: '/users',
schema: {
response: {
200: USER_SCHEMA.array(),
},
},
handler: (req, res) => {
res.send([]);
},
});
});