Back to Projects
library

Fastify Zod

A fluent, type-safe validation and request lifecycle layer for Fastify v5+ with Zod schemas, chained pre-handlers, custom async checks, and flexible error formatting.

Fastify Zod

Overview

Fastify Zod (@explita/fastify-zod) is a high-performance plugin that brings developer-first, type-safe schema validation to Fastify v5+. Engineered to streamline API development, it validates incoming request bodies, route parameters, headers, and query strings with Zod while preserving 100% end-to-end TypeScript type inference directly onto request.body, request.params, and request.query.

The package introduces a fluent chaining API (app.schema().pre().check().post()) alongside a standalone route builder (defineRoute(fastify, schema)). Developers can declare schemas once and cleanly chain authentication or authorization pre-handlers via .pre() before executing validation routines, avoiding boilerplate middleware duplication and enabling reusable route definitions across multiple HTTP verbs (get, post, put, patch, delete).

Beyond standard schema validation, Fastify Zod provides custom check functions (both synchronous and async) for business logic rules like database uniqueness or permission checks. The built-in reject() utility simplifies error returns (reject("Invalid input") or reject({ field: "error" })), while multiPathError() enables granular, nested-field error mapping.

Configurable for production resilience, the plugin supports multiple error formatting styles (simple, flat, detailed, or custom user formatters), configurable failure hints, and a soft validation mode (soft: true) to safely inspect issues without throwing fatal errors.

Tech Stack

backend

TypeScriptFastifyZod@explita/fastify-zodNode.js

Tags

#TypeScript#Fastify#Zod#Validation#API#Plugin#REST#Backend#NPM Package#Library