Fastify is a Node.js framework that focuses on providing exceptional performance when building web applications, especially APIs.
It offers a series of features that allow us to develop scalable and fast applications, with minimal overhead and an intuitive structure.
Among the highlighted features of Fastify are,
- High-level performance: Fastify is designed to handle a large number of requests per second with efficient resource usage.
- Easy routing: Allows defining routes in a simple and clear way.
- Plugin support: Facilitates the integration of additional functionalities through an extensible plugin system.
- Efficient error handling: Provides mechanisms to manage errors effectively and in a customized way.
- Data optimization and validation: Includes tools to validate and optimize request data.
For more details and documentation about Fastify, you can visit the official repository on GitHub - fastify/fastify. Here we will find additional examples and the complete documentation.
How to Install Fastify
To start using Fastify, we must install it in our Node.js project. We can do this easily via npm, the Node.js package manager. Let’s make sure we have Node.js and npm installed, and then run the following command to add Fastify to our project:
npm install fastify
This command will download and install the Fastify library in our node_modules directory and add it to the dependencies in our package.json file.
How to Use Fastify
Once we have installed Fastify, we can start using it to build our API. Next, we will see how to create a basic server, define routes, and handle requests using Fastify.
Create a Basic Server
First, let’s create a file called server.mjs in our project. In this file, we will configure a basic server using Fastify:
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
// Example GET route
fastify.get('/hello', async (request, reply) => {
reply.type('application/json').code(200)
return { hello: 'world' }
})
// Example POST route
fastify.post('/echo', async (request, reply) => {
return request.body;
});
fastify.listen({ port: 5000 }, (err, address) => {
if (err) throw err
// Server is now listening on ${address}
})
In this code:
- We use
Fastifyto create an instance of the Fastify server with log support. - We define two routes: a GET route at
/hellothat returns a simple greeting and a POST route at/echothat returns the content sent in the request. - Finally, we start the server on port 3000 and display a message in the console to confirm it is running.
Error Handling
Fastify offers a robust system for handling errors. We can catch global errors and customize error responses. Here is an example of how to define a global error handler:
fastify.setErrorHandler((error, request, reply) => {
fastify.log.error(error);
reply.status(500).send({ error: 'Internal Server Error' });
});
In this example, we are catching all unhandled errors and responding with a generic error message and a 500 status code.
Using Plugins
Fastify has a plugin system that allows us to extend the framework’s functionality. We can add plugins to handle data validation, authentication, and much more. For example, to add a plugin that validates request bodies, we could do the following:
const Fastify = require('fastify');
const fastify = Fastify({ logger: true });
// Plugin for data validation
fastify.register(require('fastify-schema-validation'), {
// Plugin configuration
});
// POST route with data validation
fastify.post('/register', {
schema: {
body: {
type: 'object',
required: ['username', 'password'],
properties: {
username: { type: 'string' },
password: { type: 'string' }
}
}
}
}, async (request, reply) => {
return { message: 'User registered successfully' };
});
In this example, we register a schema validation plugin and define a POST route that validates the request body according to a JSON schema.

