Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 39 ยท Schemas and Validation

Type Providers and TypeBox

Get static TypeScript types from your Fastify JSON Schemas: type providers, TypeBox, Static types, response typing and how it compares with Zod.

A JSON Schema validates data at runtime. TypeScript checks types at compile time. Without help you must write both: a schema for Fastify and an interface for your handler, and keep them in sync by hand. Change one, forget the other, and the compiler can no longer protect you. A type provider removes the duplication: you write the schema once and TypeScript infers request.body, request.query, request.params and even the reply type from it.

This lesson explains the idea, shows the most popular provider (TypeBox), and lets you run the schema-building part on the site. The real packages (fastify, @sinclair/typebox, @fastify/type-provider-typebox) need npm, so the TypeScript snippets are read-only. The runnable examples use a tiny hand-written Type helper that produces exactly the same kind of object TypeBox does.

The problem

TypeScript
// Hand-written types and schemas: two sources of truth
interface CreateUser { name: string; age: number }

app.post<{ Body: CreateUser }>('/users', {
  schema: { body: { type: 'object', required: ['name', 'age'], properties: { name: { type: 'string' }, age: { type: 'integer' } } } },
}, async (request) => {
  request.body.name; // typed because we *said* it is CreateUser
});

The generic { Body: CreateUser } is a promise you make to the compiler. Nothing checks that the schema really produces a CreateUser. If you later add email to the schema but not to the interface, TypeScript stays silent.

TypeBox: schemas that are also types

TypeBox is a library for building JSON Schema in code. A TypeBox schema is a plain JSON Schema object, so Fastify and Ajv accept it unchanged. TypeScript also understands the builder calls, and Static<typeof Schema> turns a schema into its TypeScript type:

TypeScript
import { Type, type Static } from '@sinclair/typebox';

const CreateUser = Type.Object({
  name: Type.String({ minLength: 1 }),
  age: Type.Integer({ minimum: 0 }),
  email: Type.Optional(Type.String({ format: 'email' })),
});

type CreateUser = Static<typeof CreateUser>;
// { name: string; age: number; email?: string | undefined }

One definition; the runtime schema and the compile-time type cannot drift apart.

Because the builder only returns plain objects, you can see exactly what it does. Run this stand-in Type helper (a few lines imitating TypeBox's output) and compare the result with the hand-written schema from the first lesson:

Node.js What a TypeBox-style builder produces

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The two schemas are identical. That is the whole trick: TypeBox adds nothing at runtime beyond building objects. All of its value is in the TypeScript types attached to those calls.

Wiring it into Fastify

A type provider tells Fastify's types how to read the schema option. For TypeBox you install @fastify/type-provider-typebox and call withTypeProvider:

TypeScript
import Fastify from 'fastify';
import { Type } from '@sinclair/typebox';
import type { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';

const app = Fastify().withTypeProvider<TypeBoxTypeProvider>();

app.post('/users', {
  schema: {
    body: Type.Object({ name: Type.String(), age: Type.Integer() }),
    querystring: Type.Object({ dryRun: Type.Optional(Type.Boolean()) }),
    response: {
      201: Type.Object({ id: Type.Integer(), name: Type.String() }),
    },
  },
}, async (request, reply) => {
  request.body.name;        // string
  request.body.age;         // number
  request.query.dryRun;     // boolean | undefined
  return reply.code(201).send({ id: 1, name: request.body.name });   // checked against the 201 schema
});

No generics, no interfaces. If you misspell request.body.nmae, the compiler complains. If the 201 reply is missing id, the compiler complains. Inside a plugin, remember that withTypeProvider applies to the instance you call it on, so a plugin usually starts with const typed = app.withTypeProvider<TypeBoxTypeProvider>(), or you declare the provider type once on the plugin's parameter.

Runtime and compile time stay consistent

Two properties make this safe:

  1. Fastify still validates at runtime with the same schema, so a request that violates the types never reaches your handler.
  2. The reply is typed too. The response schemas constrain what reply.send() accepts, so returning a wrong shape is a compile error (and the serializer drops undeclared fields at runtime).

Here is the earlier route running on the stand-in, with the schema built by the stand-in Type:

Node.js A route whose schema comes from a Type builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Reusing schemas and types together

Combine TypeBox with the shared schema idea by exporting one module per resource: the schema value and the static type under the same name.

TypeScript
// schemas/user.ts
import { Type, type Static } from '@sinclair/typebox';

export const User = Type.Object({
  id: Type.Integer(),
  name: Type.String(),
  email: Type.String({ format: 'email' }),
});
export type User = Static<typeof User>;

export const CreateUser = Type.Omit(User, ['id']);
export type CreateUser = Static<typeof CreateUser>;

export const UpdateUser = Type.Partial(CreateUser);

Type.Omit, Type.Pick and Type.Partial derive variants and keep the types in step, which replaces the hand-written spread trick from the previous lesson. Services take and return User, routes use User and CreateUser as schemas, and tests import the same names.

Alternatives

Approach Schema language Notes
TypeBox JSON Schema Closest to Fastify's model; schemas are plain JSON Schema
json-schema-to-ts provider JSON Schema you write by hand Infers types from as const schemas; no new library syntax
Zod (fastify-type-provider-zod) Zod Great if your team already uses Zod; compiled to JSON Schema for docs
Plain generics ({ Body: ... }) Any Simple but two sources of truth

Pick one and use it everywhere. Mixing three approaches in one codebase is the real maintenance cost.

Common mistakes

  • Forgetting withTypeProvider, then wondering why request.body is unknown.
  • Using Type.Optional outside Type.Object. It only affects the required list of the object that contains it.
  • Letting types lie. A cast (as User) in a handler turns off the protection. Let inference do the work.
  • Putting secrets in the type of a response. The response schema decides what leaves the server; do not include passwordHash in it.
  • Expecting types to validate. Types vanish at runtime. The schema validates; the type is a free by-product.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is a TypeBox schema at runtime?

    TypeBox only builds plain JSON Schema objects. The TypeScript types attached to the builder calls exist only at compile time.
  2. 2. What does Static<typeof Schema> give you?

    Static converts a TypeBox schema type into the TypeScript type of the data it describes.
  3. 3. Why use a type provider instead of generics like app.post<{ Body: CreateUser }>?

    With generics you write a type and a schema separately. A type provider derives the type from the schema.
  4. 4. If a TypeBox response schema for status 201 requires id, what happens when a handler calls reply.code(201).send({ name: 'x' })?

    With a type provider the reply type is derived from the response schema, so a missing required field is caught by the compiler.

Summary

  • Type providers let TypeScript infer request.body, query, params and replies from the route schema.
  • TypeBox builds plain JSON Schema objects, so Fastify and Ajv use them unchanged; Static<typeof S> gives the matching type.
  • Enable it with Fastify().withTypeProvider<TypeBoxTypeProvider>() (read-only here; the stand-in builder shows the same objects).
  • Type.Omit, Type.Pick and Type.Partial derive create and update variants from one definition.
  • Runtime validation still comes from the schema; types are a compile-time bonus.

Next: Plugins and register()