BrilworksarrowBlogarrowProduct Engineering

How to Build APIs with Node.js and Fastify

Hitesh Umaletiya
Hitesh Umaletiya
July 21, 2025
Clock icon3 mins read
Calendar iconLast updated July 21, 2025
How-to-Build-APIs-with-Node.js-and-Fastify-banner-image
Quick Summary:- Node.js is a popular choice for building fast, scalable APIs, and Fastify makes the process even smoother. This guide shows you how to set up and build APIs using Node.js and Fastify, covering core features like routing, plugins, and performance.

Node.js is one of the most popular technologies for API development. It's fast and lightweight. Running on an ultra-fast V8 engine, Node.js facilitates JavaScript-based backend development. It has been used in a wide range of services, real-time apps, single-page applications, CLI, and IoT projects.

In addition, a wealth of Nodejs frameworks makes the development smooth and faster. Fastify, one of the frameworks built on top of Node, is known for its speed and minimalistic nature. As the name suggests, it focuses on speed, but its real value shows in how it handles validation, routing, and performance with very little setup.

Fastify often pops up when it comes to building modern apps in no time. It borrows features from established Node frameworks, extending their capabilities and removing limitations present in traditional frameworks.

Take an example of Express, it is a default choice for a large portion of Node.js developers, and it lacks built-in input validation. Developers often have to stitch those parts together themselves. Fastify takes a different path. It gives more out-of-the-box, with less manual setup, while still keeping control in the developer's hands.

In this article, we'll build a simple API using Fastify. We'll go through the steps from setup to deployment, so you can see how the framework works in practice, without skipping over the details that matter in real projects.

Why Choose Fastify?

Fastify is popular in the Node.js ecosystem due to its performance and extensibility. This means developers can add more features without changing its core. In short, it provides a solid performance, and features like schema-based validation and a plugin system make development faster.

Why_Choose_Fastify 1753077461376

  1. Fastify is one of the fastest Node.js frameworks.
  2. Built-in support for JSON Schema validation for input handling.
  3. Fastify's provides a modular development environment with its plugin-based architecture.
  4. It includes hooks, decorators, and several other features to enhance productivity.
  5. Compared to alternatives like Express, Fastify offers superior performance and a more structured approach to building APIs.

Setting Up a Fastify Project

Here's what it requires to create an API with Fastify.

  1. Node.js (v16 or higher)
  2. npm
  3. A code editor (e.g., VS Code)

Step 1: Initialize a Node.js Project

Create a new directory for your project and initialize it:

Image 1753077706579

Step 2: Install Fastify

npm install fastify

Step 3: Create a Basic Server

Create a file named server.js:

Create_a_basic_server 1753077897382

Run the server with:

Run_the_server 1753078009721

This simple setup demonstrates Fastify's minimalistic approach to creating an API server.

Routing in Fastify

Fastify's routing system is intuitive and supports both synchronous and asynchronous handlers. Let's expand our API with more routes.

Example: User API

Create routes to manage a list of users. Update server.js:

Create_routes 1753078119538

Testing the Routes

Use a tool like Postman or curl to test the API:

Testing_the_Routes 1753078221639

Fastify's routing is clean and supports dynamic parameters, query strings, and various HTTP methods out of the box.

Schema Validation with Fastify

Fastify's JSON Schema support allows you to validate incoming requests and outgoing responses. This ensures data integrity and reduces boilerplate code.

Adding Validation

Update the POST /users route to include a schema:

Adding_Validation 1753078412777

Now, if you send an invalid request (e.g., missing name or invalid email), Fastify will return a 400 error:

Fastify_will_return_a_400_error 1753078528962

This schema-based validation ensures robust input handling without manual checks.

Middleware and Hooks

Fastify uses hooks instead of traditional middleware for lifecycle management. Hooks allow you to execute code at various stages of the request-response cycle.

Example: Logging Middleware

Add a hook to log request details:

Logging_Middleware 1753078597884

This logs every incoming request. Fastify supports hooks like onRequest, preHandler, onResponse, and more for granular control.

Example: Authentication Middleware

Simulate a simple API key check:

Authentication_Middleware 1753078831917

Test with curl:

curl http://localhost:3000/users -H "x-api-key: my-secret-key"

Without the correct API key, you'll get a 401 error.

Plugins for Modularity

Fastify's plugin system allows you to organize code into reusable modules. Let's create a plugin for user routes.

Step 1: Create a Plugin

Create users-plugin.js:

Create_users Plugin

Step 2: Register the Plugin

Update server.js:

Update_server

The routes are now modularized, making the codebase cleaner and easier to maintain.

Connecting to a Database

For a real-world API, you'll likely need a database. Let's integrate Fastify with MongoDB using the fastify-mongodb plugin.

Step 1: Install Dependencies

npm install fastify-mongodb mongodb

Step 2: Update the Plugin

Modify users-plugin.js to use MongoDB:

Update_the_Plugin_2 1753079761406

Step 3: Register MongoDB

Update server.js:

Update_server

Ensure MongoDB is running locally, and create a database named fastify_db. The API now uses MongoDB for persistent storage.

Error Handling

Fastify provides built-in error handling. You can define custom error handlers to manage errors gracefully:

Error_Handling 1753079963772

This ensures all uncaught errors return a consistent response format.

Deployment

To deploy your Fastify API, consider platforms like Heroku, AWS, or Vercel. Here's a quick guide for deploying to Vercel:

Install Vercel CLI:

Deployment 1753080064471

 

Conclusion

Fastify, combined with Node.js, provides an efficient way to build APIs. Fastify is a popular choice when it comes to building lightweight APIs with Nodejs. In this guide, we have had a brief overview of how to create a Fastify project, create routes, establish a connection with the database, and deployment. If you are looking to modernize your existing app or want to build an app with top-rated Node.js developers, connect with us today to build a web application.

Hitesh Umaletiya

Hitesh Umaletiya

Co-founder of Brilworks. As technology futurists, we love helping startups turn their ideas into reality. Our expertise spans startups to SMEs, and we're dedicated to their success.

Get In Touch

Contact us for your software development requirements

You might also like

Get In Touch

Contact us for your software development requirements