Telerik blogs

Is Fasitify the best option for making a modern Node.js API? Let’s take a look.

JavaScript has become the most popular programming language in the world. The ecosystem has grown and matured significantly in the past 10 years. Many open-source communities, projects and frameworks have been created since then and helped the language become what it is today.

The development of Node.js turned the possibility of building JavaScript to a whole new level. From something that could only run on a browser, we can build something that can run on our machine as an application. Since then, Node.js has become the easiest way to build modern and fast APIs nowadays.

The ability to build a Node.js API from scratch in minutes is what makes it so popular among developers. The ecosystem that Node.js brings to developers makes it easy to build APIs that can handle many simultaneous requests without debilitating the server.

Many frameworks have been built to help us create modern APIs using Node.js. The most famous and used is Express. Express is a minimal and flexible Node.js web application framework that provides a robust set of features to develop Node.js applications. It is the most famous Node.js framework, but Express has a few pain points that might make you reconsider using it to build your Node.js API. In its place, you should look at Fastify.

Fastify

Fastify is a modern web framework for Node.js that aims to provide the best developer experience with the least overhead and a powerful plugin architecture. It was inspired by Hapi, Restify and Express.

fastify logo

Fastify is built as a general-purpose web framework, but it shines when building extremely fast HTTP APIs that use JSON as the data format. It has the goal to improve the throughput of many web and mobile applications without compromising on throughput and performance, so anyone who wants to use it can build extremely fast HTTP APIs with low overhead.

An efficient server implies a lower cost of the infrastructure, a better responsiveness under load and happy users. How can you efficiently handle the resources of your server, knowing that you are serving the highest number of requests as possible, without sacrificing security validations and handy development?

Let’s cover a few of the features that makes Fastify so performant:

  • Fast—able to serve up to 30,000 requests per second (depending on code complexity)
  • Fully extensible via its hooks, plugins and decorators
  • Expressive and developer friendly
  • TypeScript-ready
  • JSON schema–based into a highly performant function
  • Low-cost logging

Now that we know a little about the features of Fastify, let’s create a simple API using it and understand more about what makes Fastify so special.

Getting Started

To get started with Fastify, the first thing that we should do is install Fastify:

yarn add fastify

After installing it, we can import Fastify to our file and instantiate it:

import Fastify from 'fastify';
 
const fastify = Fastify();

Logging

Fastify uses Pino as a logger. Logging is disabled by default in Fastify, but we can enable it by passing a logger property to our Fastify instance. We should be aware of this because logging is disabled by default and it’s not possible to enable it at runtime.

import Fastify from 'fastify';

const fastify = Fastify({ logger: true });

Routing

The route methods will configure the endpoints of your API, and Fastify handles it in a simple and powerful way. There’s two ways of declaring routes with Fastify: shorthand or full declaration.

The shorthand declaration is easier to write and read. It goes like this:

fastify.get(path, [options], handler);

It supports all operations such as POST, PUT, DELETE, etc. Let’s use the get operation to create our first route using Fastify. We’re going to return a simple Hello world! message on our route.

import Fastify from 'fastify';

const fastify = Fastify({ logger: true });

fastify.get('/', (req, reply) => {
  reply.send('Hello world!');
});

Fastify was inspired by Express so the syntax looks familiar. The req and reply stand for request and reply (response).

Now that we have our first route configured, it’s time for us to get our server running. For doing that, we will use the fastify.listen method. It returns a promise and we will create a function that handles this promise using async and await.

import Fastify from 'fastify';

const fastify = Fastify({ logger: true });

fastify.get('/', (req, reply) => {
  reply.send('Hello world!');
});

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

Plugins

With Fastify, everything is a plugin. It offers a plugin model similar to Hapi (another Node.js framework that inspired Fastify). It adds full encapsulation of plugins so that each plugin can use its dependencies and hooks if it wants to.

The usage of plugins with Fastify makes it easy to create reusable and decoupled APIs. It handles perfectly handles asynchronous code and guarantees the load order and the close order of the plugins.

We’re going to create our first plugin using Fastify, and for that we’re going to create another file. Let’s name our new file first_plugin, and inside that file we’re going to declare a new route.

function (fastify, opts, next) {
  fastify.get('/first', (req, reply) => {
    reply.send('First plugin using Fastify!')
  });

  next();
});

Now, inside our main file, we’re going to import our first_plugin file and use the register API, which is the core of the Fastify framework. It is the only way to add routes, plugins, etc.

import Fastify from 'fastify';

import firstPlugin from './first-plugin'

const fastify = Fastify({ logger: true });

fastify.get('/', (req, reply) => {
  reply.send('Hello world!');
});

fastify.register(firstPlugin);

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

Easy, right? Fastify has a whole ecosystem full of plugins maintained by the Fastify team that you can use.

Conclusion

Fastify has been built from the ground up to be as fast as possible and we can say that it delivers everything that we expect. Fastify is a powerful Node.js framework for creating reliable and performant modern APIs. The powerful features that it offers—such as logging, plugins, validation, serialization and fluent-schema—make it the best viable option for creating a modern Node.js API.

Fastify is a framework that is not only limited to REST architecture. We can create use it to create GraphQL and gRPC services using it and make them more performant.


Leonardo Maldonado
About the Author

Leonardo Maldonado

Leonardo is a full-stack developer, working with everything React-related, and loves to write about React and GraphQL to help developers. He also created the 33 JavaScript Concepts.

Related Posts

Comments

Comments are disabled in preview mode.