Member-only story
Server-Side Development with Fastify — Response Serialization and Request Validation Error Handling
2 min readFeb 20, 2021
Fastify is a small Node framework for developing back end web apps.
In this article, we’ll look at how to create back end apps with Fastify.
Serialization
We can change the way that responses are serialized.
To do this, we write:
const fastify = require('fastify')({})const schema = {
response: {
'2xx': {
type: 'object',
properties: {
value: { type: 'string' },
otherValue: { type: 'boolean' }
}
},
201: {
value: { type: 'string' }
}
}
}fastify.get('/', { schema }, (request, reply) => {
reply.send({ value: 1, otherValue: 'foo' })
})const start = async () => {
try {
await fastify.listen(3000, '0.0.0.0')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
We add the response schema with the schema.response
property.
We specify the response data type and structure for each status code.
The type
specifies the data type of the response.