Categories
Fastify

Server-Side Development with Fastify — Middleware and Hooks

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.

Middleware

Middleware support doesn’t come out of the box with the Fastify framework since version 3.

If we want to add support for Express style middleware, we need to install fastify-express or middle plugin.

For example, we can write:

const fastify = require('fastify')()

const start = async () => {
  try {
    await fastify.register(require('fastify-express'))
    fastify.use(require('cors')())

    fastify.get('/', function (request, reply) {
      reply.send({ hello: 'world' })
    })

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

We add:

await fastify.register(require('fastify-express'))
fastify.use(require('cors')())

to add the fastify-express plugin with the cors middleware.

To use the middle module, we write:

const fastify = require('fastify')()

const start = async () => {
  try {
    await fastify.register(require('middie'))
    fastify.use(require('cors')())

    fastify.get('/', function (request, reply) {
      reply.send({ hello: 'world' })
    })

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

to add the middleware and add the cors middleware.

Restrict Middleware Execution to a Certain Paths

We can restrict middleware execution to certain paths.

For example, we can write:

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

const start = async () => {
  try {
    await fastify.register(require('fastify-express'))
    const serveStatic = require('serve-static')

    fastify.use('/css', serveStatic(path.join(__dirname, '/assets')))
    fastify.use('/css/(.*)', serveStatic(path.join(__dirname, '/assets')))
    fastify.use(['/css', '/js'], serveStatic(path.join(__dirname, '/assets')))

    fastify.get('/', function (request, reply) {
      reply.send({ hello: 'world' })
    })

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

We call fastify.use with the path that the middleware runs in as the first argument.

The 2nd argument is the middleware that we want to run.

This doesn’t work with route with parameters.

Fastify offers some alternatives to the most commonly used middlewares, such as fastify-helmet in the case of helmet, fastify-cors for cors and fastify-static for serve-static.

Hooks

We can register hooks with the fastify.addHook method.

For example, we can write:

const fastify = require('fastify')({})
const asyncMethod = () => Promise.resolve('foo')

const start = async () => {
  try {
    fastify.addHook('onRequest', async (request, reply) => {
      await asyncMethod()
      return
    })

    fastify.get('/', function (request, reply) {
      reply.send({ hello: 'world' })
    })

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

to call addHook for the onRequest event.

Also, we can write:

const fastify = require('fastify')({})
fastify.addHook('onRequest', (request, reply, done) => {
  done()
})
const start = async () => {
  try {
    fastify.get('/', function (request, reply) {
      reply.send({ hello: 'world' })
    })

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

to do the same thing. We call done to indicate the hook has finished running.

Conclusion

We can add Express middleware and hooks with Fastify.

Leave a Reply

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