Lesson 11 / 32
Response Serialization
Speed up JSON responses by declaring response schemas that Fastify serializes only for listed fields.
Schema-based serialization
The response field in schema tells Fastify what fields to send, speeding up JSON serialization by only including declared properties.
Response schema
Define what the response looks like. Fastify will only serialize fields in the schema.
const getUserSchema = {
response: {
200: {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string' },
email: { type: 'string' },
},
},
},
};
fastify.get('/users/:id', { schema: getUserSchema }, async (req) => {
return {
id: 1,
name: 'Alice',
email: 'alice@example.com',
// password field will be stripped by serialization
};
});