Categories
Fastify

Server-Side Development with Fastify — Route Level Hooks and Decorators

Spread the love

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.

Route Level Hooks

We can add hooks at the route level.

To do this, we can write:

const fastify = require('fastify')({})

fastify.route({
  method: 'GET',
  url: '/',
  schema: { },
  onRequest (request, reply, done) {
    done()
  },
  onResponse (request, reply, done) {
    done()
  },
  preParsing (request, reply, done) {
    done()
  },
  preValidation (request, reply, done) {
    done()
  },
  preHandler (request, reply, done) {
    done()
  },
  preSerialization (request, reply, payload, done) {
    done(null, payload)
  },
  handler (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 the hooks.

onRequest is run when a request is received.

onResponse is run when a response is sent.

preParsing is run when the request is parsed.

preValidation is run before validation is done on the request.

preHandler is run after the shared preHandler hooks.

preSerialization runs after the shared preSerialization hook, which is run after the response is serialized.

handler is the route handler method.

Decorators

We can use decorators to customize core Fastify objects, such as the request and reply objects.

To add one and use them we can write:

const fastify = require('fastify')({})

fastify.decorateRequest('user', '')

fastify.addHook('preHandler', (req, reply, done) => {
  req.user = 'jane smith'
  done()
})

fastify.get('/', (req, reply) => {
  reply.send(`Hello, ${req.user}!`)
})
const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

We call fastify.decoratorRequest method to add a user property the req object.

Then we set the req.user property in the preHandler hook to 'jane smith' .

Then in our route handler, we can access the value.

Therefore, we get:

Hello, jane smith!

returned as the response.

We can use the fastify.decorate method to decorate the Fastify server instance.

For instance, we can write:

const fastify = require('fastify')({})

fastify.decorate('conf', {
  db: 'some.db',
  port: 3000
})

fastify.get('/', (req, reply) => {
  reply.send(`Hello ${fastify.conf.db}`)
})
const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

to add data to the fastify object.

We add the conf property to it.

Then we can access the value anywhere in our app.

So we should get:

Hello some.db

from the response.

The decorated Fastify server can also be accessed with the this keyword from the route handler.

For instance, we can write:

const fastify = require('fastify')({})

fastify.decorate('conf', {
  db: 'some.db',
  port: 3000
})

fastify.get('/', async function (request, reply) {
  reply.send({hello: this.conf.db})
})

const start = async () => {
  try {
    await fastify.listen(3000, '0.0.0.0')
  } catch (err) {
    fastify.log.error(err)
    process.exit(1)
  }
}
start()

Then we get:

{"hello":"some.db"}

from the response.

Conclusion

We can add data to the Fastify instance or requests with Fastify decorators.

Also, we can add hooks at the route level.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *