Developers always strive to build high-performance applications with minimal infrastructure cost. Usually, it is a trade-off between the two. However, Fastify is a web framework that aims to win on both of these factors. In this post, we will learn how to do a Fastify server setup.

This will be our first step into learning Fastify web framework from scratch.

1 – Fastify Core Features

Some of the core features of Fastify are as follows:

  • Fastify is highly performant. As per the official docs, Fastify can support upto 30K requests per second.
  • Fastify has a highly modular architecture. It is extensible using hooks, plugins and decorators.
  • Fastify is developer-friendly. It also supports Typescript to support the growing Typescript community.
  • Fastify is quite extensible. It provides features such as plugins, hooks and decorators that allow us to extend the core functionalities of Fastify.

Fastify has been adopted by several organizations. Also, the popular framework NestJS supports Fastify as one of the platforms.

2 – Installation of Fastify NPM Package

To use Fastify, we need to first install the necessary NPM package. Basically, NodeJS and NPM are pre-requisites for working with Fastify.

We create a project directory and install the fastify package as below:

$ mkdir fastify-demo-project
$ npm init -y
$ npm install fastify

Once the installation is done, we can continue further.

3 – Fastify Server Setup

To create a Fastify server instance, create a file index.js and paste the below contents into the file:

import Fastify from 'fastify'

const fastify = Fastify({
  logger: true
})

// Declare a route
fastify.get('/', function (request, reply) {
  reply.send({ hello: 'World' })
})

// Run the server
fastify.listen(3000, '0.0.0.0', function (err, address) {
  if (err) {
    fastify.log.error(err)
    process.exit(1)
  }
})

We import Fastify from the fastify package. Then, we create Fastify app instance with logger as true. For logging, Fastify uses a NodeJS logging library known as pino.

Once the application instance is ready, we create a HTTP GET route handler that returns a plain Hello, World object.

Finally, we have to bring up the server. Fastify provide the listen() method that takes a port number as input to start the Fastify server. By default, Fastify instance is started on 127.0.0.1. To access it from all IPv4 interfaces, we add 0.0.0.0 as the host property.

To start the application, we can use the command node index.js.

4 – Fastify Server using Async Await

Fastify also provides out-of-the-box support for async/await. In other words, the same application can be written using async/await.

See below example:

// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true })

fastify.get('/', async (request, reply) => {
  return { hello: 'World' }
})

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

As you can see, the route handler now uses async keyword. Also, while starting the server, we use async await to call the listen() method.

Another important thing to note is the use of require while importing the fastify package. Basically, we can use both CommonJS and Javascript ESM approach to write our actual code. Fastify works fine with either option.

Conclusion

Fastify is quite promising as an alternative to Express. It improves on performance and modularity of applications.

In the next post, we will look at one of the building blocks of Fastify applications i.e. Fastify Plugins.

In case you want to build a bigger application using Fastify, check out this post on creating a Fastify REST API with Postgres.

If you have any comments or queries about this post, please feel free to mention them in the comments section below.

Categories: BlogFastify

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

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