Validation with schemas (TypeBox)
Seventh chapter of the "Fastify with TypeScript" series. The previous chapter ended with two problems: generics describe the data but don't check it (limit + 1 gave us 51), and where a schema does check it, the schema and the TypeScript interface are two copies kept in sync by hand. In this chapter we describe the data once, with TypeBox, and get both the runtime validation and the types from that single description.
Fastify uses JSON Schema to validate requests and to serialize responses. TypeBox lets you write that JSON Schema with a small, typed API, and derives the matching TypeScript type from it. We already used it in chapter 4 for the configuration. What's new is the type provider, the piece that connects TypeBox to Fastify's types:
npm install typebox @fastify/type-provider-typebox
typebox is already in your package.json from chapter 4, so npm only adds the type provider; it's in the command so that this chapter also works if you start from here.
Since version 1.0 TypeBox is published as
typebox(the old package was@sinclair/typebox).@fastify/type-provider-typebox6.x requires the new one.
Schemas as the single source of truth
Replace the content of src/users/users.schema.ts, which held the hand-written JSON Schema from chapter 5, with:
// src/users/users.schema.ts
import { Type, type Static } from 'typebox';
export const UserRole = Type.Union([
Type.Literal('admin'),
Type.Literal('user'),
Type.Literal('moderator'),
]);
export const UserParams = Type.Object({
id: Type.String({ format: 'uuid' }),
});
export const ListUsersQuery = Type.Object({
limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 100 })),
});
export const CreateUserBody = Type.Object({
name: Type.String({ minLength: 1, maxLength: 100 }),
email: Type.String({ format: 'email' }),
password: Type.String({ minLength: 8 }),
});
// No password here: anything not declared is stripped from the response.
export const UserResponse = Type.Object({
id: Type.String({ format: 'uuid' }),
name: Type.String(),
email: Type.String(),
role: UserRole,
});
export const ErrorResponse = Type.Object({
error: Type.String(),
});
export type Role = Static<typeof UserRole>; // 'admin' | 'user' | 'moderator'
export type CreateUserBodyType = Static<typeof CreateUserBody>;
export type UserResponseType = Static<typeof UserResponse>;
Each Type.* call builds a piece of JSON Schema, and the constraints you'd expect are options: minLength, format, minimum. Type.Optional marks a property that may be missing. At the bottom, Static<typeof ...> turns a schema into a TypeScript type, so UserResponseType is { id: string; name: string; email: string; role: 'admin' | 'user' | 'moderator' } without anyone writing it.
The user now has a role and the body asks for a password: we'll need both when authentication arrives in chapter 12.
The type provider
Tell Fastify once that your schemas are TypeBox schemas, and every route will infer its types from its schema option. In src/app.ts, add the import:
import type { TypeBoxTypeProvider } from '@fastify/type-provider-typebox';
and chain withTypeProvider() on the Fastify() call:
const app = Fastify({
logger: { level: config.LOG_LEVEL },
...opts,
}).withTypeProvider<TypeBoxTypeProvider>();
Now the routes. Replace the content of src/users/users.route.ts with:
// src/users/users.route.ts
import { Type } from 'typebox';
import type { FastifyPluginAsyncTypebox } from '@fastify/type-provider-typebox';
import {
CreateUserBody,
ErrorResponse,
ListUsersQuery,
UserParams,
UserResponse,
type UserResponseType,
} from './users.schema.ts';
const userRoutes: FastifyPluginAsyncTypebox = async (fastify) => {
// Temporary in-memory storage: PostgreSQL replaces it in chapter 13
const users: UserResponseType[] = [];
fastify.get('/', {
schema: {
querystring: ListUsersQuery,
response: { 200: Type.Array(UserResponse) },
},
}, async (request) => {
const { limit = 10 } = request.query; // a number: validated and converted by the schema
return users.slice(0, limit);
});
fastify.get('/:id', {
schema: {
params: UserParams,
response: { 200: UserResponse, 404: ErrorResponse },
},
}, async (request, reply) => {
const user = users.find((u) => u.id === request.params.id);
if (!user) {
return reply.code(404).send({ error: 'User not found' });
}
return user;
});
fastify.post('/', {
schema: {
body: CreateUserBody,
response: { 201: UserResponse },
},
}, async (request, reply) => {
// The password is validated but not stored yet: hashing arrives in chapter 12
const { name, email } = request.body;
const user: UserResponseType = { id: crypto.randomUUID(), name, email, role: 'user' };
users.push(user);
reply.code(201);
reply.header('Location', `/api/v1/users/${user.id}`);
return user;
});
};
export default userRoutes;
Compare it with the previous chapter. The three interfaces (ListUsersRoute, GetUserRoute, CreateUserRoute) and the <...> after each method are gone: request.query, request.params, request.body and the reply are all typed from the schema right above the handler. FastifyPluginAsyncTypebox is the plugin type that carries the type provider into the fastify parameter, which is what makes the inference work inside a route file.
This is why the series keeps routes and handlers together in users.route.ts: an inline handler gets its types from the schema next to it, so there is no interface to write and nothing that can drift.
Try it
curl -X POST localhost:3000/api/v1/users \
-H 'content-type: application/json' \
-d '{"name":"Grace","email":"grace@example.com","password":"correct-horse"}'
# {"id":"1c3aafd3-80d0-400a-be03-d565567180ea","name":"Grace","email":"grace@example.com","role":"user"}
curl -X POST localhost:3000/api/v1/users \
-H 'content-type: application/json' \
-d '{"name":"Grace","email":"grace@example.com","password":"short"}'
# {"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"body/password must NOT have fewer than 8 characters"}
Params and query string are validated too, which they never were before:
curl localhost:3000/api/v1/users/nope
# {"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"params/id must match format \"uuid\""}
curl "localhost:3000/api/v1/users?limit=abc"
# {"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"querystring/limit must be integer"}
curl "localhost:3000/api/v1/users?limit=1000"
# {"statusCode":400,"code":"FST_ERR_VALIDATION","error":"Bad Request","message":"querystring/limit must be <= 100"}
Remember the experiment that closed the previous chapter? Repeat it: add console.log(typeof limit, limit + 1); as the second line of the GET / handler and call curl "localhost:3000/api/v1/users?limit=5". The terminal now prints:
number 6
The query string still arrives as text, but Fastify converts it according to the schema before your handler runs. The type says number and this time it is true. Remove the console.log before going on.
The types come from the schema
Because the types are derived from the schemas, the compiler checks your handlers against them. Two changes to try with npm run typecheck (undo each one afterwards).
In the POST handler, give the new user a role that doesn't exist, role: 'superuser':
error TS2322: Type '"superuser"' is not assignable to type '"admin" | "user" | "moderator"'.
In the GET /:id handler, answer with a status code the schema doesn't declare, reply.code(500):
error TS2345: Argument of type '500' is not assignable to parameter of type '200 | 404'.
There is one case the compiler lets through on purpose: returning more than the schema declares. Change the last line of the POST handler to:
return { ...user, password: request.body.password };
It compiles, and yet the response is unchanged:
# {"id":"785f687f-6aa7-41fe-aa2f-5d4f89b427cf","name":"Grace","email":"grace@example.com","role":"user"}
Fastify serializes the reply through the response schema, and any field the schema doesn't declare is left out. This is the safety net that will keep password_hash from ever leaving the server when our users come from a database row. Put return user; back.
Extracting a handler
If you move a handler into a named function, the inference from the route no longer reaches it. Use the Static types with the generics from the previous chapter:
import type { FastifyRequest, FastifyReply } from 'fastify';
import type { CreateUserBodyType, UserResponseType } from './users.schema.ts';
interface CreateUserRoute {
Body: CreateUserBodyType;
Reply: { 201: UserResponseType };
}
export async function createUser(
request: FastifyRequest<CreateUserRoute>,
reply: FastifyReply<CreateUserRoute>,
) {
// ...
}
The interface is back, but it is built from the schema's types, so there is still only one description of the data.
Your schemas are also your API contract
The schemas you just wrote describe the API precisely: which routes exist, what they accept, what they return. That is exactly what an OpenAPI document is, so there is no reason to write one by hand. @fastify/swagger builds it from the route schemas:
npm install @fastify/swagger
In src/app.ts, add the import:
import swagger from '@fastify/swagger';
and, inside buildApp(), replace the /health route with:
// The OpenAPI document is generated from the route schemas: register it before any route
app.register(swagger, {
openapi: {
openapi: '3.1.0',
info: { title: 'My Fastify App', version: '1.0.0' },
},
});
app.get('/openapi.json', { schema: { hide: true } }, async () => app.swagger());
app.get('/health', { schema: { hide: true } }, async () => ({ status: 'ok' }));
The plugin must be registered before the routes, because it collects them as they are declared. hide: true keeps a route out of the document. Finally, in users.route.ts, add tags: ['users'], as the first line of each of the three schema objects, to group the operations:
schema: {
tags: ['users'],
body: CreateUserBody,
response: { 201: UserResponse },
},
curl localhost:3000/openapi.json
In the output you'll find POST /api/v1/users/ with a request body that requires name, email and password, and GET /api/v1/users/ with an optional integer limit between 1 and 100: the same TypeBox schemas that validate the requests, not a second copy that can go out of date.
The real payoff is on the other side of the API. Whoever consumes it (a frontend, another service) can generate a typed client instead of writing one by hand:
curl -s localhost:3000/openapi.json > openapi.json
npx openapi-typescript openapi.json -o api-types.d.ts
The generated file contains every path, every body and every response as TypeScript types, down to role: "admin" | "user" | "moderator". When you change a schema on the server and regenerate, the client stops compiling wherever it no longer matches. Run the generator with npx rather than installing it in this project: at the time of writing it depends on TypeScript 5, and npm install would refuse to put it next to our TypeScript 6.
This is the code-first approach: the code is the source of truth and the document is derived from it. The alternative is API-first, where the OpenAPI document is written and agreed on before the implementation. API-first suits teams that design the contract together with its consumers; code-first is quicker to start and, with schemas as the single source, cannot drift from the implementation.
Why you should always define a response schema
Three reasons, all of which you have now seen. A response schema lets Fastify serialize with fast-json-stringify, which is faster than JSON.stringify because it knows the shape in advance. It strips every field you didn't declare, so sensitive data can't leak by accident. And it types the handler's return value and documents the route in the OpenAPI contract. From here on, every route in this series has one.
⬅️ Previous chapter: TypeScript generics in routes · ➡️ Next chapter: Plugins and encapsulation
This article is part of the "Fastify with TypeScript" series — chapter 7 of 18.
Top comments (0)