Categories
Fastify

Server-Side Development with Fastify — Reply Serializer, Route Prefix, and Not Found Handler

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.

Close the Server

We can call fastify.close to close the server.

For example, we can write:

const fastify = require('fastify')()

fastify.get('/', (request, reply) => {
  reply.send('hello world')
})

fastify.ready(err => {
  if (err) throw err
})

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

to call fastify.close without an argument, which will return a promise.

Route Prefix

We can add a route prefix to our tours with the prefix option.

For instance, we can write:

const fastify = require('fastify')()

fastify.register(function (instance, opts, done) {
  instance.get('/foo', function (request, reply) {
    request.log.info('prefix: %s', instance.prefix)
    reply.send({ prefix: instance.prefix })
  })

  instance.register(function (instance, opts, done) {
    instance.get('/bar', function (request, reply) {
      request.log.info('prefix: %s', instance.prefix)
      reply.send({ prefix: instance.prefix })
    })

    done()
  }, { prefix: '/v2' })

  done()
}, { prefix: '/v1' })

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

Then when we go to /v1/v2/bar , we see:

{
  "prefix": "/v1/v2"
}

returned. And if we go to /v1/foo , we see:

{
  "prefix": "/v1"
}

Set Reply Serializer

We can call the setReplySerializer method to set the reply serializer for all routes.

For instance, we can write:

const fastify = require('fastify')()

fastify.setReplySerializer(function (payload, statusCode){
  return `status: ${statusCode}, content: ${payload}`
})

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)
    await fastify.close()
    process.exit(1)
  }
}
start()

to add the serializer into our app.

Set Not Found Handler

We can set a handler for handler 404 errors.

For example, we can write:

const fastify = require('fastify')()

fastify.setNotFoundHandler({
  preValidation: (req, reply, done) => {
    done()
  },
  preHandler: (req, reply, done) => {
    done()
  }
}, function (request, reply) {
    reply.send('not found')
})

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)
    await fastify.close()
    process.exit(1)
  }
}
start()

to call setNotFoundHandler on the server instance.

We can also set the not found handler on a group of URLs.

For instance, we can write:

const fastify = require('fastify')()

fastify.register(function (instance, options, done) {
  instance.setNotFoundHandler(function (request, reply) {
    return reply.send('not found')
  })
  done()
}, { prefix: '/v1' })

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)
    await fastify.close()
    process.exit(1)
  }
}
start()

to add a not found handler for the routes that starts with /v1 .

Conclusion

We can close the server, set route prefixes, set not found handlers, and set a reply serializer with Fastify.

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 *