Skip to content

Setup

This example demonstrates how to configure Fastify to use Zod schemas to validate incoming queries and serialize responses, powered by fastify‑type‑provider‑zod.

You’ll see how to:

  • Enable runtime validation of querystring and ensure responses comply with declared Zod types.
  • Infer full TypeScript types for request and response data via .withTypeProvider<ZodTypeProvider>().
  • Seamlessly integrate validatorCompiler and serializerCompiler from the plugin for unified schema enforcement

This setup keeps your route definitions clean and type-safe, using a single source of truth for schema, validation, and typing.

ts
import type { ZodTypeProvider } from '@marcalexiei/fastify-type-provider-zod';
import {
  serializerCompiler,
  validatorCompiler,
} from '@marcalexiei/fastify-type-provider-zod';
import Fastify from 'fastify';
import { z } from 'zod';

const app = Fastify();

// Add schema validator and serializer
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(serializerCompiler);

app.withTypeProvider<ZodTypeProvider>().route({
  method: 'GET',
  url: '/',
  // Define your schema
  schema: {
    querystring: z.object({
      name: z.string().min(4),
    }),
    response: {
      200: z.string(),
    },
  },
  handler: (req, res) => {
    res.send(req.query.name);
  },
});

app.listen({ port: 4949 });

Customize serializer

INFO

You can also pass options to the serializerCompiler function:

ts
export type ZodSerializerCompilerOptions = {
  replacer?: (this: any, key: string, value: any) => any;
};
ts
import {
  createSerializerCompiler,
  validatorCompiler,
  type ZodSerializerCompilerOptions,
} from '@marcalexiei/fastify-type-provider-zod';
import Fastify from 'fastify';

const app = Fastify();

const replacer: ZodSerializerCompilerOptions['replacer'] = function (
  key,
  value,
) {
  if (this[key] instanceof Date) {
    return { _date: value.toISOString() };
  }
  return value;
};

// Create a custom serializer compiler
const customSerializerCompiler = createSerializerCompiler({ replacer });

// Add schema validator and serializer
app.setValidatorCompiler(validatorCompiler);
app.setSerializerCompiler(customSerializerCompiler);

// ...

app.listen({ port: 4949 });