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.
Error Handler and Query String Options
Fastify has lots of server options we can configure.
The trustProxy
option lets Fastify know that it’s sitting behind a proxy.
We can set it to an IP address of the proxy server or a boolean.
Also, we can create a function to set the return the proxy IPs to trust.
We can access the ip
, ips
, hostname
and protocol
values on the [request](https://medium.com/r/?url=https%3A%2F%2Fwww.fastify.io%2Fdocs%2Flatest%2FRequest)
object:
let i = 0
const fastify = require('fastify')({
genReqId (req) { return i++ }
})
fastify.get('/', (request, reply) => {
console.log(request.ip)
console.log(request.ips)
console.log(request.hostname)
console.log(request.protocol)
reply.send('hello world')
})
const start = async () => {
try {
await fastify.listen(3000, '0.0.0.0')
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
ip
has the IP address. hostname
has the hostname, protocol
has the protocol.
The querystringParser
option lets us set the query string parser we want to use.
For example, we can write:
const qs = require('qs')
const fastify = require('fastify')({
querystringParser: str => qs.parse(str)
})
fastify.get('/', (request, reply) => {
reply.send('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 use the qs.parse
method to parse query strings to an object.
The versioning
option lets us version our routes with semver versioning.
We can set this option by writing:
const versioning = {
storage () {
let versions = {}
return {
get: (version) => { return versions[version] || null },
set: (version, store) => { versions[version] = store },
del: (version) => { delete versions[version] },
empty: () => { versions = {} }
}
},
deriveVersion: (req, ctx) => {
return req.headers['accept']
}
}
const fastify = require('fastify')({
versioning
})
fastify.get('/', (request, reply) => {
reply.send('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 add the get
, set
, and del
methods to add the manipulate the versions
object to work with the versions.
frameworkErrors
lets us provide error handlers for errors our app encounters.
For example, we can write:
const fastify = require('fastify')({
frameworkErrors (error, req, res) {
if (error instanceof FST_ERR_BAD_URL) {
res.code(400)
return res.send("Provided url is not valid")
} else {
res.send(err)
}
}
})
fastify.get('/', (request, reply) => {
reply.send('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 add our own handler for the bad URL error.
And we return a 400 error if we encounter it.
The clientErrorHandler
lets us listen to error events emitted by the client connection and returns a 400 error.
For instance, we can write:
const fastify = require('fastify')({
clientErrorHandler (err, socket) {
const body = JSON.stringify({
error: {
message: 'Client error',
code: '400'
}
})
this.log.trace({ err }, 'client error')
socket.end(`HTTP/1.1 400 Bad RequestrnContent-Length: ${body.length}rnContent-Type: application/jsonrnrn${body}`)
}
})
fastify.get('/', (request, reply) => {
reply.send('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 add our own clientErrorHandler
to add client-side errors.
Conclusion
We can add various handlers to our Fasttify app.