Read More
🎉Celebrating 25 Years of Tech Excellence and Trust - Learn More
Quick Summary: Ever heard about the Fastify framework? Fastify is a NodeJS framework used for backend web development. It has a powerful plugin, architecture, and minimal overhead. It is also known as one of the fastest Node.js web frameworks. And to know more about Fastify, you need to read this blog. Hope you like it!
Let’s start this blog with numbers because who doesn’t like numbers (and huge numbers)? So, if you’re a software developer or belong to a tech background or NodeJS is your first love, the next line might be exciting for you. This is all for suspense – according to stats, Node JS is the most popular and widely used, adored web development tool in the US, with over 6.3 million websites utilizing it. Whoa, remarkable!
As you are familiar with Node.js development, I'm sure you know a bit about Express or have worked with it. You must be wondering why I'm so sure. It's because Express was the most trusted web framework for Node.js developers since its inception in 2010. Quite long, isn't it? However, things do change, and nothing lasts forever. So, in recent times, there is the emergence of more modernistic, efficient Node.js web frameworks. This led to a reduction in the use and popularity of the Express framework.
So, is there any framework in the talks or gaining the attention of developers? Well, yes, there is.
It's Fastify. It is a new player in the game and quickly gaining popularity due to its unique features and speed, making Node.js development more efficient.
Build Faster Web Apps with Radixweb’s Fastify Development Services
Contact Us Today
However, there's still an ongoing debate on Fastify vs Express, but this has to end. So, if you're still using Express, believe me, it’s the best time to switch to the Fastify framework. And if you want to know why? I have your answer in the form of this short and sweet, yet essential Fastify tutorial. Here, we'll explore the basics of the Fastify framework, including, what is Fastify, different Fastify features, why use Fastify, and most importantly we'll try to end the debate on Fastify vs Express.
Since Fastify is a highly technical subject, we need to understand some of the basic technical concepts of the Fastify framework. So, here, I’ll familiarize you with the most important Fastify plugins, and how to set up your Fastify server with a few code examples. Therefore, this Fastify tutorial will be like a sack of knowledge involving all the significant basics for your next Nodejs project. And I bet by the end of this Fastify tutorial, you’ll understand why it's named among the top NodeJS frameworks.
A Pro Tip: So before moving forward with the Fastify tutorial, I would recommend you go through our blog on understanding Node.js and its business benefits . It will help you understand all the basic concepts of Node.js development and why it’s important for business growth. It will ease your path to understanding Fastify more appropriately.
So, why wait? Let’s dive in and see what Fastify has to offer!
I know the most significant question popping into your mind – what is Fastify?
Fastify is a NodeJS framework used for backend web development. It has a powerful plugin architecture and minimal overhead. But why was Fastify developed? Fastify was born out of the requirement to build a multipurpose web framework that could offer developers a wonderful experience without bargaining on performance and throughput. Fastify framework was first motivated by Expressjs and Hapi. It is now known as one of the fastest Node.js web frameworks.
Looking at the history of the Fastify Node.js framework, David Mark Clements and Matteo Collina created Fastify in late 2016s. The latest Fastify version 4.17.0 was published in April 2023.
Want to know some exciting facts? Fastify NPM (Node Package Manager) is currently used in 25,000 Nodejs projects and is downloaded more than 700,000 times per week. Huge conglomerates like Microsoft, Protect, Seven Senders, etc. are using Fastify architecture in their tech stack. Isn’t it amazing?
Here’s the deal – You can go through some of the best Fastify examples here – Fastify examples.
Thank me later!
Fastify comes with a wide range of noteworthy features, and this is one of the upper-hand Fastify has when differentiating between Fastify vs Express. Let’s look at them.
Decorators enable backend developers to customize key Fastify objects including any request and reply to objects and the server instance used throughout the HTTP request lifecycle. Decorators API is an efficient Fastify feature used to attach different property types to the key Fastify framework objects, for example, native types, plain objects, and functions.
Fastify JS framework offers a setErrorHandler()
approach allowing you to clearly define a function for starting error handling. Furthermore, you can also define different error handlers using Fastify plugins. Fastify framework seeks to identify as many uncaught errors as taking care of the Fastify performance. This includes:
app.get(‘/’, async () => { throw new Error(‘kaboom’) })
app.get(‘/’, () => { throw new Error(‘kaboom’) })
Fastify uses a quick and adaptable logger - Pino. The Fastify server instance makes available the logger instance ( such as Fastify.log.info(“…”)
) and on all Request objects (such as request.log.info(“…”)
);
Therefore, using a logger is easy and simple. Remember to enable it as it is disabled as default:
const fastify = require('fastify')({
logger: true
})
You can use it like this:
fastify.get("/", (request, reply) => {
request.log.info("Info about request");
reply.send({ message: "hello world" });});
Fastify uses Ajv
behind the walls allowing you to determine the validation protocols with JSON schema.
The Fastify TypeScript type declaration file manages and maintains the TypeScript community support.
Experience a Scalable Backend Development with the Best Fastify Development Company
Enjoy Our Fastify Services
But the main question is – why use Fastify? What advantages does it provide over Express?
The following section of the Fastify tutorial will answer all your questions, especially about why you use Fastify when developing NodeJS applications.
Based on my observation as a software developer, I would like to list the advantages I enjoy when working with the Fastify Nodejs framework. Let’s go through them:
Easy to Develop - Ease of development is one of the biggest advantages of using Fastify, providing it a plus point in the Fastify vs Express debate. You can easily run your Fastify app directly in your local environment. The execution does not require any extra tools and the same code can be executed in your decided serverless platform with just some extra snippet of code.
Good Maintenance - Fastify is a web framework with low overhead. It helps to reduce the support and maintenance costs for the entire Nodejs application. This eventually helps in minimizing the overall cost of Node.js development. Moreover, the Fastify framework highly focuses on better security that ensures data validation and an automatic security system.
Flexibility - Have you ever heard about Fastify TypeScript? Wondering what is Fastify TypeScript? Okay, I'm here! So, the Fastify JS framework supports TypeScript that communicates with its API with the help of GraphQL adapter and collaborates with AWS (Amazon Web Services) Lambda. As an outcome, it is the best choice for API interface development and web application development. Also, to have a better idea of the Fastify TypeScript concept, I’ll be giving a basic Fastify TypeScript example in the next part of the blog (a little more wait, please).
Higher Performance - I'm sure by now you've got an idea about the speed of the Fastify JS framework (see the name itself FASTify). Along with the speed, the Fastify framework is also popular for its high scalability, making it an ideal choice for both small and large backend development projects. The JSON format examines the Fastify functions automatically, guaranteeing an efficient Fastify route for data packets throughout the network. That’s what makes the Fastify framework like the fastest whirlwind.
So, here comes my favorite and most important part of our Fastify tutorial – Fastify vs Express. It’s important to understand the difference between them, as they are both popular Node.js web frameworks loved and adored by software developers worldwide.
Let’s have a look.
When differentiating between Fastify vs Express, each web framework has its pros and cons. Nothing is perfect in the world! And it's also not that easy to compare these diverse and top Nodejs frameworks. However, I’ve still tried to pick some important yet relevant assessment criteria, so that it helps you decide between Fastify vs Express.
However, we need to upgrade ourselves from time to time, and software developers at Radixweb ace it. Our Nodejs developers try to upgrade themselves with every changing trend and technology. Moreover, they’ve seamlessly adopted the Fastify framework and acquired a thorough knowledge of the subject (which can be of immense help to you).
Coming back to the topic, let’s now talk about Fastify vs Express.
1. Speed and Scalability – In the case of Express, it processes a minimal number of requests per second. That means it can manage 15,978 requests per second. On the other hand, the Fastify framework is known for its best benchmark results with 78,956 requests per second.
2. TypeScript Support – We’ve already gone through the Fastify TypeScript term both in Fastify features and advantages. You can see the significance of Fastify TypeScript, right? So, Fastify is the only framework that supports TypeScript, depending on the Node.js version you’re using. On the other hand, several challenges occur when Express supports TypeScript.
3. Plugins Availability – When comparing Fastify to Express, the Fastify framework is the only one that comes with several plugins. Yes, it’s a major point in Fastify vs Express! Fastify plugins are a big-big boon for developers as they become independent of multiple packages and frameworks for efficient application development. This is the reason Fastify is a one-stop destination.
As it's quite clear-cut, the Fastify framework provides several advantages over Express, making it a more suitable choice for developing Node.js applications. So, here, we put an end to the debate – Fastify vs Express, for now, of course.
Willing to Build Robust and Scalable Web Apps Utilizing Best Node.js frameworks?
Opt Node.js Development
Here we end the first part of our blog. There we discussed all the basic and easy-peasy concepts of the Fastify framework. And I hope you enjoyed it! Now comes a bit important and technical part of our Fastify tutorial. In the following section, we’ll learn about the vital Fastify plugins and how to implement Fastify NPM and server.
So, ready? Let’s face it.
Besides the wide range of features that the Fastify framework provides, it also consists of strong plugin architecture. Moreover, any app developer can create plugins that function well with Fastify. These Fastify plugins help to develop quick building blocks for bootstrapping your API project.
Fastify plugins built by external developers fall into the class of community plugins, on the other hand, the Fastify plugins maintained by the Fastify team are known as core plugins. An important note - It's crucial that any community plugin must follow Fastify’s best practices.
In essence, the Fastify team enthusiastically manages and maintains these core plugins. The developers highly benefit from using these core Fastify plugins during Node.js backend development.
Let’s now go through some significant Fastify plugins:
1. fastify-jwt - This Fastify plugin helps decorate your web application using a standard JSON web token. Fastify-jwt uses the jsonwebtoken package internally.
2. fastify-nextjs - Nextjs is a React framework for producing pre-rendering websites on the server side. This plugin helps developers do the same with the Fastify framework.
3. fastify-redis - This Fastify plugin allows your Fastify app to share a similar Redis connection across the server.
4. fastify-auth - Fastify team created this authentication plugin. This Fastify plugin enables the developers to rapidly inject authentication logic into the API routes.
5. fastify-cors - Do you know cross-origin requests are crucial for any app, Fastify plugins like fastify-cors help you manage this without the requirement for a separate CORS package installation.
Talking about installation, here is a small guide on how to install Node.js and NPM on Windows and Mac. Believe me, when I say this, this guide will help you immensely.
Now comes the most important and most technical part of our blog. Here, we’ll learn to implement the Fastify framework.
This Fastify documentation is all about how to set up your Fastify framework involving some important Fastify examples. Radixweb’s Nodejs development team has specifically curated these Fastify examples for a better understanding both for newbies and experts.
Get Fastify NPM:
npm install fastify
Then create server.js and add the following content:
// Require the framework and instantiate it
const fastify = require('fastify')({ logger: true })
// Declare a route
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
// Run the server!
const start = async () => {
try {
await fastify.listen({ port: 3000 })
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
Now, tell me, do you prefer to use async/await? Don't worry! Fastify supports both of them right off the boat.
Finally, launch the server with:
node server
And you can also test it with:
curl <http://localhost:3000>
Yes, that’s it! You’ve got your first Fastify server up and running. Congratulations!
Get fastify-CLI with NPM:
npm install --global fastify-cli
Then scaffold a new project with:
fastify generate myproject
Of course, Fastify can do a lot more than this.
For example, you can easily integrate input and output validation utilizing JSON Schema. It helps to carry out unique functionalities before the execution of the handler:
const fastify = require('fastify')({ logger: true })
fastify.route({
method: 'GET',
url: '/',
schema: {
// request needs to have a querystring with a `name` parameter
querystring: {
type: 'object',
properties: {
name: { type: 'string'}
},
required: ['name'],
},
// the response needs to be an object with a `hola` property of type 'string'
response: {
200: {
type: 'object',
properties: {
hola: { type: 'string' }
}
}
}
},
// this function is executed for every request before the handler is executed
preHandler: async (request, reply) => {
// E.g. check authentication
},
handler: async (request, reply) => {
return { hola: 'world' }
}
})
const start = async () => {
try {
await fastify.listen({ port: 3000 })
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
Fastify is delivered with a typings file, but you still may require installing @types/node
, all depends on your current version of Node.js.
The following Fastify example builds an http server.
We need to pass the appropriate typings for our current http version.
By passing types we get rightly typed access to the fundamental http objects in Fastify routes.
If using http2 we'd pass <http2.Http2Server, http2.Http2ServerRequest, http2.Http2ServerResponse>
For https pass http2.Http2SecureServer
or http.SecureServer
instead of a Server.
This ensures that during the server handler, we also get http.ServerResponse
with accurate typings on reply.res
.
import Fastify, { FastifyInstance, RouteShorthandOptions } from 'fastify'
import { Server, IncomingMessage, ServerResponse } from 'http'
const server: FastifyInstance = Fastify({})
const opts: RouteShorthandOptions = {
schema: {
response: {
200: {
type: 'object',
properties: {
pong: {
type: 'string'
}
}
}
}
}
}
server.get('/ping', opts, async (request, reply) => {
return { pong: 'it worked!' }
})
const start = async () => {
try {
await server.listen({ port: 3000 })
const address = server.server.address()
const port = typeof address === 'string' ? address : address?.port
} catch (err) {
server.log.error(err)
process.exit(1)
}
}
start()
These were some of the most basic yet most important Fastify examples every developer needs to understand.
Accelerate Your App’s Time-to-Market with Node.js Experts on Deck
Let Node.js Experts Help
As you've already seen, Fastify is quite promising as an alternative to the Express framework. And we've also differentiated the frameworks Fastify vs Express. Now you'd understand why Fastify won the debate. Fastify JS framework helps to enhance the modularity and performance of your applications. Every software developer seeks to develop high-performance apps with the lowest infrastructure cost (and why not). And mostly it is a compromise between the two, which means either you get better performance or minimal infrastructure cost.
But, for all the best reasons, we now have Fastify. This NodeJS web framework's main goal is to ace both these key factors.
In this blog, we came across several aspects of Fastify, including what is Fastify, its key features, why use Fastify, and the difference between Fastify vs Express. Then moving on to bit technical part, we discussed the most significant Fastify plugins and how to set up the Fastify NPM and server. So, I'm quite sure now you would know why Fastify is the best Nodejs framework and why it's necessary for all Node.js developers. Therefore, I hope you try it in your next Node.js project.
Experience the Best of Fastify with Radixweb!Wondering if using Fastify is easy or challenging?To be honest, using the Fastify JS framework is not everyone’s cup of tea. You need to have a good knowledge of all the basics and important concepts related to it. However, if you want to focus on other major operations, Radixweb is always happy to help. It is a top-notch Fastify development company, having good expertise in different Fastify development concepts, whether be Fastify NPM, Fastify TypeScript, and many more.You can take advantage of Radixweb’s Fastify development services to create a robust, modern, and lightweight server-side web app. Our Fastify developers are proficient in designing and developing best-in-class applications. So, you can rely on our services completely.Because we believe – your success is our success.So, why wait? If you’re eager to learn and discuss more about the Fastify framework or want to build an app using the Fastify framework, reach out to us now.
Bhadresh is a senior technocrat and works as a Project Domineer for Radixweb. He is an AWS certified solution engineer with 12 years of experience. He specializes in technologies like ReactJs, NodeJs, AngularJs and has driven successful projects with clean code architecture, PgSql database system and REST architecture for the web.
Ready to brush up on something new? We've got more to read right this way.