Modern APIs With Fastify in Node.js (2024)

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.

Modern APIs With Fastify in Node.js (1)

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.

As an enthusiast with demonstrable knowledge in the realm of Node.js and web frameworks, let's delve into the article's content and explore the concepts used:

1. JavaScript Ecosystem Growth:

The article rightly points out that JavaScript has become the most popular programming language globally over the last decade. The ecosystem has expanded significantly, fostering the development of various open-source communities, projects, and frameworks.

2. Node.js Evolution:

The development of Node.js marked a transformative shift, allowing developers to use JavaScript beyond the confines of browsers. It enables the creation of applications that can run on machines, making it a preferred choice for building modern and fast APIs.

3. Node.js Frameworks:

Express, acknowledged as the most famous Node.js framework, is mentioned in the article. It's described as a minimal and flexible web application framework with a robust feature set. However, the article suggests that Express has some pain points, paving the way for an alternative — Fastify.

4. Introduction to Fastify:

Fastify is presented as a modern web framework for Node.js. Inspired by Hapi, Restify, and Express, it prioritizes delivering an optimal developer experience with minimal overhead and a powerful plugin architecture.

5. Fastify Features:

The article highlights key features that contribute to Fastify's performance:

  • Speed: Capable of serving up to 30,000 requests per second, depending on code complexity.
  • Extensibility: Achieved through hooks, plugins, and decorators.
  • Expressive and Developer-Friendly: A focus on enhancing the developer experience.
  • TypeScript-Ready: Compatibility with TypeScript.
  • JSON Schema-Based: Utilizes JSON schema for highly performant functions.
  • Low-Cost Logging: Efficient logging using Pino, which is disabled by default.

6. Getting Started with Fastify:

The article provides a step-by-step guide on installing and initializing Fastify, including details on logging configuration and routing.

7. Routing in Fastify:

Fastify's routing is discussed, with emphasis on two declaration methods: shorthand and full declaration. A simple route example using the shorthand method is presented.

8. Fastify Plugins:

The concept that everything in Fastify is treated as a plugin is introduced. Plugins are highlighted as a means to achieve encapsulation, reusability, and orderly handling of asynchronous code. An example of creating and using a plugin is demonstrated.

9. Conclusion:

The article concludes by asserting that Fastify is purpose-built for speed, offering powerful features like logging, plugins, validation, serialization, and fluent-schema. It positions Fastify as the best viable option for creating reliable and performant modern Node.js APIs, not limited to REST architecture but extending to GraphQL and gRPC services.

In summary, the article provides a comprehensive overview of the evolution of Node.js, introduces Fastify as a modern framework, and demonstrates its key features and usage through practical examples.

Modern APIs With Fastify in Node.js (2024)
Top Articles
Latest Posts
Article information

Author: Pres. Lawanda Wiegand

Last Updated:

Views: 5797

Rating: 4 / 5 (51 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Pres. Lawanda Wiegand

Birthday: 1993-01-10

Address: Suite 391 6963 Ullrich Shore, Bellefort, WI 01350-7893

Phone: +6806610432415

Job: Dynamic Manufacturing Assistant

Hobby: amateur radio, Taekwondo, Wood carving, Parkour, Skateboarding, Running, Rafting

Introduction: My name is Pres. Lawanda Wiegand, I am a inquisitive, helpful, glamorous, cheerful, open, clever, innocent person who loves writing and wants to share my knowledge and understanding with you.