Lesson 11 / 30

Response Serialization

Control how responses are serialized to JSON for performance.

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
  };
});