Fastify response schemas make APIs faster and safer
A response schema is validation, documentation, and a serialization speed-up in one place.
Anish KumarBackend#nodejs#fastify#api
Most people add schemas to Fastify routes to validate the request body. The response schema is just as useful:
app.get(
"/users/:id",
{
schema: {
response: {
200: {
type: "object",
properties: { id: { type: "string" }, name: { type: "string" } },
},
},
},
},
handler,
);- Faster serialization. Fastify compiles the schema into a serializer, which is quicker than
JSON.stringify. - No accidental leaks. Properties not in the schema are dropped, so a
passwordHashon the user object never reaches the client. - Free documentation. The same schemas generate OpenAPI docs with
@fastify/swagger.