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.
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.
Here's what it requires to create an API with Fastify.
Create a new directory for your project and initialize it:
npm install fastify
Create a file named server.js:
Run the server with:
This simple setup demonstrates Fastify's minimalistic approach to creating an API server.
Fastify's routing system is intuitive and supports both synchronous and asynchronous handlers. Let's expand our API with more routes.
Create routes to manage a list of users. Update server.js:
Use a tool like Postman or curl to test the API:
Fastify's routing is clean and supports dynamic parameters, query strings, and various HTTP methods out of the box.
Fastify's JSON Schema support allows you to validate incoming requests and outgoing responses. This ensures data integrity and reduces boilerplate code.
Update the POST /users route to include a schema:
Now, if you send an invalid request (e.g., missing name or invalid email), Fastify will return a 400 error:
This schema-based validation ensures robust input handling without manual checks.
Fastify uses hooks instead of traditional middleware for lifecycle management. Hooks allow you to execute code at various stages of the request-response cycle.
Add a hook to log request details:
This logs every incoming request. Fastify supports hooks like onRequest, preHandler, onResponse, and more for granular control.
Simulate a simple API key check:
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.
Fastify's plugin system allows you to organize code into reusable modules. Let's create a plugin for user routes.
Create users-plugin.js:
Update server.js:
The routes are now modularized, making the codebase cleaner and easier to maintain.
For a real-world API, you'll likely need a database. Let's integrate Fastify with MongoDB using the fastify-mongodb plugin.
npm install fastify-mongodb mongodb
Modify users-plugin.js to use MongoDB:
Update server.js:
Ensure MongoDB is running locally, and create a database named fastify_db. The API now uses MongoDB for persistent storage.
Fastify provides built-in error handling. You can define custom error handlers to manage errors gracefully:
This ensures all uncaught errors return a consistent response format.
To deploy your Fastify API, consider platforms like Heroku, AWS, or Vercel. Here's a quick guide for deploying to Vercel:
Install Vercel CLI:
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.
Get In Touch
Contact us for your software development requirements
Get In Touch
Contact us for your software development requirements