Response Serialization
// Fastify serializes responses based on the response schema\napp.get('/users', {\n schema: {\n response: {\n 200: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n id: { type: 'integer' },\n name: { type: 'string' },\n email: { type: 'string', format: 'email' },\n createdAt: { type: 'string', format: 'date-time' },\n },\n },\n },\n },\n },\n}, async () => {\n return users.map(user => ({\n id: user.id,\n name: user.name,\n email: user.email,\n createdAt: user.created_at.toISOString(),\n }));\n});\n\n// Custom serializer\napp.setSerializerCompiler(({ schema, method, url, httpStatus }) => {\n return (data) => {\n if (schema) {\n // Use AJV to serialize according to schema\n return JSON.stringify(schema);\n }\n return JSON.stringify(data);\n };\n});\n\n// Exclude fields from response\napp.get('/user/:id', {\n schema: {\n response: {\n 200: {\n type: 'object',\n properties: {\n id: { type: 'integer' },\n name: { type: 'string' },\n email: { type: 'string' },\n },\n // password is automatically excluded\n // because it is not in the response schema\n },\n },\n },\n}, async (request) => {\n const user = await findUser(request.params.id);\n // password_hash will be stripped by serialization\n return user;\n});
Examples
const Fastify = require('fastify');
const app = Fastify({ logger: true });
// Define response schemas
const schemas = {
userResponse: {
type: 'object',
properties: {
id: { type: 'integer' },
name: { type: 'string' },
email: { type: 'string' },
role: { type: 'string', enum: ['user', 'admin'] },
},
},
listResponse: {
type: 'object',
properties: {
data: {
type: 'array',
items: { \$ref: 'userResponse#' },
},
total: { type: 'integer' },
page: { type: 'integer' },
},
},
};
app.get('/users', {
schema: {
response: {
200: schemas.listResponse,
},
},
}, async () => ({
data: [
{ id: 1, name: 'Alice', email: '[email protected]', role: 'admin', password: 'secret' },
{ id: 2, name: 'Bob', email: '[email protected]', role: 'user', password: 'hidden' },
],
total: 2,
page: 1,
}));
app.listen({ port: 3000 }, () => {
console.log('Server with serialization running');
});