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.
Installation
We install the fastify
package by running:
npm i fastify --save
with NPM or:
yarn add fastify
with Yarn.
First App
We create a simple server app with a few lines of code.
For example, we can write:
const fastify = require('fastify')({
logger: true
})
fastify.get('/', (request, reply) => {
reply.send({ hello: 'world' })
})
fastify.listen(3000, '0.0.0.0', (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
fastify.log.info(`server listening on ${address}`)
})
to create a simple server with the /
route.
logger
set to true
enables the built-in logger.
reply.send
sends a response.
fastify.listen
starts the app and listens to the server.
The first argument is the port, the 2nd argument is the IP address to listen for requests from. '0.0.0.0'
listens to all addresses.
When we go to /
, we see:
{"hello":"world"}
returned.
We can also use astbc
and await
in our router handlers.
For example, we can write:
const fastify = require('fastify')({
logger: true
})
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
const start = async () => {
try {
await fastify.listen(3000, '0.0.0.0')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
We just return the object we want as the response.
And we call fastify.listen
without the callback.
Validate Request Data
We can validate request data by passing in an option to our route.
For example, we can write:
const fastify = require('fastify')({
logger: true
})
const opts = {
schema: {
body: {
type: 'object',
properties: {
foo: { type: 'string' },
bar: { type: 'number' }
}
}
}
}
fastify.post('/', opts, async (request, reply) => {
return { hello: 'world' }
})
const start = async () => {
try {
await fastify.listen(3000, '0.0.0.0')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
to create our schema and then pass in the properties into it.
We specify the types of the foo
and bar
properties.
This lets us specify the properties that are accepted.
Serializing Data
We can also specify the schema for the response.
For example, we can write:
const fastify = require('fastify')({
logger: true
})
const opts = {
schema: {
response: {
200: {
type: 'object',
properties: {
hello: { type: 'string' }
}
}
}
}
}
fastify.post('/', opts, async (request, reply) => {
return { hello: 'world' }
})
const start = async () => {
try {
await fastify.listen(3000, '0.0.0.0')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
to specify the response that’s returned by the /
route.
Run Our Server
We can run our Fastify app with the Fastify CLI.
We install it by running:
npm i fastify-cli
Then in package.json
, we add:
{
"scripts": {
"start": "fastify start server.js"
}
}
Then we run it with:
npm start
Conclusion
We can create a simple back end Node web app easily with Fastify.