Top Related Projects
Fast, unopinionated, minimalist web framework for node.
A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
Expressive middleware for node.js using ES2017 async functions
The Simple, Secure Framework Developers Trust
The API and real-time application framework
Connect is a middleware layer for Node.js
Quick Overview
Fastify is a high-performance, low overhead web framework for Node.js. It is designed to be extensible and focuses on providing an excellent developer experience while maintaining top-tier performance.
Pros
- Extremely fast performance, often outperforming other popular Node.js frameworks
- Highly extensible plugin system
- Built-in support for JSON Schema validation
- Asynchronous by default, leveraging Node.js's async capabilities
Cons
- Smaller ecosystem compared to more established frameworks like Express
- Steeper learning curve for developers new to Node.js or coming from other frameworks
- Less comprehensive documentation compared to some more mature frameworks
- May be overkill for very simple applications or microservices
Code Examples
- Basic server setup:
const fastify = require('fastify')({ logger: true })
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
const start = async () => {
try {
await fastify.listen({ port: 3000 })
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
}
start()
- Using JSON Schema for request validation:
const opts = {
schema: {
body: {
type: 'object',
properties: {
name: { type: 'string' },
age: { type: 'integer' }
},
required: ['name', 'age']
}
}
}
fastify.post('/user', opts, async (request, reply) => {
return { status: 'User created' }
})
- Using plugins:
const fastify = require('fastify')()
const fastifySwagger = require('@fastify/swagger')
fastify.register(fastifySwagger, {
exposeRoute: true,
routePrefix: '/docs',
swagger: {
info: { title: 'Test API', version: '1.0.0' }
}
})
// Your routes here
fastify.listen({ port: 3000 }, (err) => {
if (err) throw err
console.log('Server running on http://localhost:3000')
})
Getting Started
To get started with Fastify:
-
Install Fastify:
npm install fastify
-
Create a new file (e.g.,
server.js
) and add the following code:const fastify = require('fastify')({ logger: true }) fastify.get('/', async (request, reply) => { return { hello: 'world' } }) const start = async () => { try { await fastify.listen({ port: 3000 }) } catch (err) { fastify.log.error(err) process.exit(1) } } start()
-
Run the server:
node server.js
Your Fastify server is now running on http://localhost:3000
.
Competitor Comparisons
Fast, unopinionated, minimalist web framework for node.
Pros of Express
- Mature ecosystem with extensive middleware and plugins
- Large community and widespread adoption
- Flexible and unopinionated, allowing for diverse architectural choices
Cons of Express
- Lower performance compared to more modern frameworks
- Callback-based architecture can lead to "callback hell"
- Lack of built-in TypeScript support
Code Comparison
Express:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
Fastify:
const fastify = require('fastify')()
fastify.get('/', async (request, reply) => {
return 'Hello World!'
})
Key Differences
- Performance: Fastify is generally faster and more efficient
- TypeScript: Fastify has built-in TypeScript support
- Plugins: Fastify uses a plugin system for extending functionality
- Validation: Fastify includes built-in request/response validation
- Async/Await: Fastify natively supports async/await patterns
Conclusion
While Express remains popular due to its maturity and flexibility, Fastify offers improved performance, modern features, and built-in TypeScript support. The choice between them depends on project requirements, team expertise, and performance needs.
A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
Pros of Nest
- Comprehensive, opinionated framework with built-in dependency injection
- Strong TypeScript support and decorators for cleaner code structure
- Extensive ecosystem with official packages for various integrations
Cons of Nest
- Steeper learning curve due to its complexity and Angular-inspired architecture
- Potentially slower performance compared to Fastify's lightweight approach
- More boilerplate code required for simple applications
Code Comparison
Nest:
@Controller('cats')
export class CatsController {
@Get()
findAll(): string {
return 'This action returns all cats';
}
}
Fastify:
fastify.get('/cats', async (request, reply) => {
return 'This action returns all cats';
});
Key Differences
- Nest uses decorators and classes for defining routes and controllers, while Fastify uses a more functional approach
- Nest provides a modular structure with built-in dependency injection, whereas Fastify relies on plugins for extensibility
- Fastify focuses on performance and minimal overhead, while Nest prioritizes a full-featured framework with more abstractions
Conclusion
Choose Nest for large, complex applications that benefit from its structured approach and extensive features. Opt for Fastify when performance is crucial and you prefer a lightweight, flexible framework with less overhead.
Expressive middleware for node.js using ES2017 async functions
Pros of Koa
- Lightweight and minimalist design, allowing developers to add only the middleware they need
- Excellent support for ES6 features, including async/await
- Highly extensible with a wide range of middleware available
Cons of Koa
- Steeper learning curve due to its minimalist nature and reliance on middleware
- Less out-of-the-box functionality compared to Fastify
- Smaller community and ecosystem compared to Fastify
Code Comparison
Koa:
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Fastify:
const fastify = require('fastify')();
fastify.get('/', async (request, reply) => {
return 'Hello World';
});
fastify.listen(3000);
Both frameworks offer simple and concise ways to create a basic server and handle routes. Koa uses middleware-based approach, while Fastify uses a more traditional route-handler pattern. Fastify's code is slightly more explicit in defining routes, which can be beneficial for larger applications. Koa's use of ctx
object provides a unified interface for request and response, which some developers find more intuitive.
The Simple, Secure Framework Developers Trust
Pros of Hapi
- More mature and battle-tested, with a longer history in production environments
- Extensive plugin ecosystem and built-in features for enterprise-level applications
- Strong focus on configuration over convention, offering fine-grained control
Cons of Hapi
- Generally slower performance compared to Fastify
- Steeper learning curve and more verbose configuration
- Less active development and community engagement in recent years
Code Comparison
Hapi:
const Hapi = require('@hapi/hapi');
const server = Hapi.server({ port: 3000 });
server.route({
method: 'GET',
path: '/',
handler: (request, h) => 'Hello World!'
});
await server.start();
Fastify:
const fastify = require('fastify')({ logger: true });
fastify.get('/', async (request, reply) => {
return 'Hello World!'
});
await fastify.listen({ port: 3000 });
Both Hapi and Fastify are popular Node.js web frameworks, but they have different design philosophies. Hapi focuses on configuration and extensibility, making it suitable for large-scale applications with complex requirements. Fastify, on the other hand, prioritizes performance and simplicity, making it an excellent choice for microservices and high-throughput applications. The code comparison shows that Fastify has a more concise syntax for basic routing, while Hapi's approach is more explicit and configurable.
The API and real-time application framework
Pros of Feathers
- Built-in support for real-time events and WebSockets
- Modular architecture with a plugin system for easy extensibility
- Supports multiple databases and ORMs out of the box
Cons of Feathers
- Steeper learning curve due to its opinionated structure
- Can be overkill for simple REST APIs
- Slightly slower performance compared to Fastify
Code Comparison
Feathers:
const feathers = require('@feathersjs/feathers');
const app = feathers();
app.use('/users', {
async find() {
return [{ id: 1, name: 'John' }];
}
});
Fastify:
const fastify = require('fastify')();
fastify.get('/users', async (request, reply) => {
return [{ id: 1, name: 'John' }];
});
Key Differences
- Feathers provides a more comprehensive framework with built-in services and hooks
- Fastify focuses on high performance and low overhead
- Feathers has better support for real-time applications
- Fastify offers more flexibility in routing and plugin system
Use Cases
- Choose Feathers for complex, real-time applications with multiple data sources
- Opt for Fastify when building high-performance REST APIs or microservices
Both frameworks are excellent choices for Node.js development, with Feathers excelling in full-stack applications and Fastify shining in lightweight, high-speed scenarios.
Connect is a middleware layer for Node.js
Pros of Connect
- Mature and battle-tested middleware framework with a long history
- Simple and lightweight design, focusing on core functionality
- Extensive ecosystem of middleware packages
Cons of Connect
- Less active development and fewer recent updates
- Limited built-in features compared to modern frameworks
- Lacks some performance optimizations found in newer alternatives
Code Comparison
Connect:
var connect = require('connect');
var http = require('http');
var app = connect();
app.use(function(req, res){
res.end('Hello from Connect!');
});
http.createServer(app).listen(3000);
Fastify:
const fastify = require('fastify')();
fastify.get('/', async (request, reply) => {
return 'Hello from Fastify!';
});
fastify.listen(3000, (err) => {
if (err) throw err;
console.log('Server listening on 3000');
});
Summary
Connect is a lightweight middleware framework with a simple design and extensive ecosystem. It's mature and battle-tested but has seen less active development recently. Fastify, on the other hand, is a modern, high-performance web framework with built-in features and optimizations. The code comparison shows Connect's middleware-based approach versus Fastify's route-based structure, highlighting the differences in their design philosophies.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
An efficient server implies a lower cost of the infrastructure, 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 possible, without sacrificing security validations and handy development?
Enter Fastify. Fastify is a web framework highly focused on providing the best developer experience with the least overhead and a powerful plugin architecture. It is inspired by Hapi and Express and as far as we know, it is one of the fastest web frameworks in town.
The main
branch refers to the Fastify v5
release.
Check out the 4.x
branch for v4
.
Table of Contents
- Quick start
- Install
- Example
- Core features
- Benchmarks
- Documentation
- Ecosystem
- Support
- Team
- Hosted by
- License
Quick start
Create a folder and make it your current working directory:
mkdir my-app
cd my-app
Generate a fastify project with npm init
:
npm init fastify
Install dependencies:
npm i
To start the app in dev mode:
npm run dev
For production mode:
npm start
Under the hood npm init
downloads and runs Fastify
Create, which in turn uses the
generate functionality of Fastify CLI.
Install
To install Fastify in an existing project as a dependency:
npm i fastify
Example
// Require the framework and instantiate it
// ESM
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
// CommonJs
const fastify = require('fastify')({
logger: true
})
// Declare a route
fastify.get('/', (request, reply) => {
reply.send({ hello: 'world' })
})
// Run the server!
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
// Server is now listening on ${address}
})
With async-await:
// ESM
import Fastify from 'fastify'
const fastify = Fastify({
logger: true
})
// CommonJs
const fastify = require('fastify')({
logger: true
})
fastify.get('/', async (request, reply) => {
reply.type('application/json').code(200)
return { hello: 'world' }
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) throw err
// Server is now listening on ${address}
})
Do you want to know more? Head to the Getting Started
.
If you learn best by reading code, explore the official demo.
Note
.listen
binds to the local host,localhost
, interface by default (127.0.0.1
or::1
, depending on the operating system configuration). If you are running Fastify in a container (Docker, GCP, etc.), you may need to bind to0.0.0.0
. Be careful when listening on all interfaces; it comes with inherent security risks. See the documentation for more information.
Core features
- Highly performant: as far as we know, Fastify is one of the fastest web frameworks in town, depending on the code complexity we can serve up to 76+ thousand requests per second.
- Extensible: Fastify is fully extensible via its hooks, plugins, and decorators.
- Schema-based: even if it is not mandatory we recommend using JSON Schema to validate your routes and serialize your outputs. Internally Fastify compiles the schema in a highly performant function.
- Logging: logs are extremely important but are costly; we chose the best logger to almost remove this cost, Pino!
- Developer friendly: the framework is built to be very expressive and help developers in their daily use without sacrificing performance and security.
Benchmarks
Machine: EX41S-SSD, Intel Core i7, 4Ghz, 64GB RAM, 4C/8T, SSD.
Method:: autocannon -c 100 -d 40 -p 10 localhost:3000
* 2, taking the
second average
Framework | Version | Router? | Requests/sec |
---|---|---|---|
Express | 4.17.3 | ✓ | 14,200 |
hapi | 20.2.1 | ✓ | 42,284 |
Restify | 8.6.1 | ✓ | 50,363 |
Koa | 2.13.0 | ✗ | 54,272 |
Fastify | 4.0.0 | ✓ | 77,193 |
- | |||
http.Server | 16.14.2 | ✗ | 74,513 |
These benchmarks taken using https://github.com/fastify/benchmarks. This is a synthetic "hello world" benchmark that aims to evaluate the framework overhead. The overhead that each framework has on your application depends on your application. You should always benchmark if performance matters to you.
Documentation
Getting Started
Guides
Server
Routes
Encapsulation
Logging
Middleware
Hooks
Decorators
Validation and Serialization
Fluent Schema
Lifecycle
Reply
Request
Errors
Content Type Parser
Plugins
Testing
Benchmarking
How to write a good plugin
Plugins Guide
HTTP2
Long Term Support
TypeScript and types support
Serverless
Recommendations
Ecosystem
- Core - Core plugins maintained by the Fastify team.
- Community - Community-supported plugins.
- Live Examples - Multirepo with a broad set of real working examples.
- Discord - Join our discord server and chat with the maintainers.
Support
Please visit Fastify help to view prior support issues and to ask new support questions.
Version 3 of Fastify and lower are EOL and will not receive any security or bug fixes.
Fastify's partner, HeroDevs, provides commercial security fixes for all unsupported versions at https://herodevs.com/support/fastify-nes. Fastify's supported version matrix is available in the Long Term Support documentation.
Contributing
Whether reporting bugs, discussing improvements and new ideas, or writing code, we welcome contributions from anyone and everyone. Please read the CONTRIBUTING guidelines before submitting pull requests.
Team
Fastify is the result of the work of a great community. Team members are listed in alphabetical order.
Lead Maintainers:
- Matteo Collina, https://twitter.com/matteocollina, https://www.npmjs.com/~matteo.collina
- Tomas Della Vedova, https://twitter.com/delvedor, https://www.npmjs.com/~delvedor
- KaKa Ng, https://www.npmjs.com/~climba03003
- Manuel Spigolon, https://twitter.com/manueomm, https://www.npmjs.com/~eomm
- James Sumners, https://twitter.com/jsumners79, https://www.npmjs.com/~jsumners
Fastify Core team
- Aras Abbasi, https://www.npmjs.com/~uzlopak
- Harry Brundage, https://twitter.com/harrybrundage, https://www.npmjs.com/~airhorns
- Matteo Collina, https://twitter.com/matteocollina, https://www.npmjs.com/~matteo.collina
- Gürgün DayıoÄlu, https://www.npmjs.com/~gurgunday
- Tomas Della Vedova, https://twitter.com/delvedor, https://www.npmjs.com/~delvedor
- Carlos Fuentes, https://twitter.com/metcoder95, https://www.npmjs.com/~metcoder95
- Vincent Le Goff
- Luciano Mammino, https://twitter.com/loige, https://www.npmjs.com/~lmammino
- KaKa Ng, https://www.npmjs.com/~climba03003
- Luis Orbaiceta, https://twitter.com/luisorbai, https://www.npmjs.com/~luisorbaiceta
- Maksim Sinik, https://twitter.com/maksimsinik, https://www.npmjs.com/~fox1t
- Manuel Spigolon, https://twitter.com/manueomm, https://www.npmjs.com/~eomm
- James Sumners, https://twitter.com/jsumners79, https://www.npmjs.com/~jsumners
Fastify Plugins team
- Harry Brundage, https://twitter.com/harrybrundage, https://www.npmjs.com/~airhorns
- Simone Busoli, https://twitter.com/simonebu, https://www.npmjs.com/~simoneb
- Dan Castillo, https://www.npmjs.com/~dancastillo
- Matteo Collina, https://twitter.com/matteocollina, https://www.npmjs.com/~matteo.collina
- Gürgün DayıoÄlu, https://www.npmjs.com/~gurgunday
- Tomas Della Vedova, https://twitter.com/delvedor, https://www.npmjs.com/~delvedor
- Carlos Fuentes, https://twitter.com/metcoder95, https://www.npmjs.com/~metcoder95
- Vincent Le Goff
- Jean Michelet, https://www.npmjs.com/~jean-michelet
- KaKa Ng, https://www.npmjs.com/~climba03003
- Maksim Sinik, https://twitter.com/maksimsinik, https://www.npmjs.com/~fox1t
- Frazer Smith, https://www.npmjs.com/~fdawgs
- Manuel Spigolon, https://twitter.com/manueomm, https://www.npmjs.com/~eomm
Emeritus Contributors
Great contributors to a specific area of the Fastify ecosystem will be invited to join this group by Lead Maintainers when they decide to step down from the active contributor's group.
- Tommaso Allevi, https://twitter.com/allevitommaso, https://www.npmjs.com/~allevo
- Ethan Arrowood, https://twitter.com/arrowoodtech, https://www.npmjs.com/~ethan_arrowood
- ÃaÄatay Ãalı, https://twitter.com/cagataycali, https://www.npmjs.com/~cagataycali
- David Mark Clements, https://twitter.com/davidmarkclem, https://www.npmjs.com/~davidmarkclements
- dalisoft, https://twitter.com/dalisoft, https://www.npmjs.com/~dalisoft
- Dustin Deus, https://twitter.com/dustindeus, https://www.npmjs.com/~starptech
- Denis Fäcke, https://twitter.com/serayaeryn, https://www.npmjs.com/~serayaeryn
- Rafael Gonzaga, https://twitter.com/_rafaelgss, https://www.npmjs.com/~rafaelgss
- Trivikram Kamat, https://twitter.com/trivikram, https://www.npmjs.com/~trivikr
- Ayoub El Khattabi, https://twitter.com/ayoubelkh, https://www.npmjs.com/~ayoubelk
- Cemre Mengu, https://twitter.com/cemremengu, https://www.npmjs.com/~cemremengu
- Salman Mitha, https://www.npmjs.com/~salmanm
- Nathan Woltman, https://twitter.com/NathanWoltman, https://www.npmjs.com/~nwoltman
Hosted by
We are an At-Large Project in the OpenJS Foundation.
Sponsors
Support this project by becoming a SPONSOR! Fastify has an Open Collective page where we accept and manage financial contributions.
Acknowledgments
This project is kindly sponsored by:
Past Sponsors:
This list includes all companies that support one or more team members in maintaining this project.
License
Licensed under MIT.
For your convenience, here is a list of all the licenses of our production dependencies:
- MIT
- ISC
- BSD-3-Clause
- BSD-2-Clause
Top Related Projects
Fast, unopinionated, minimalist web framework for node.
A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
Expressive middleware for node.js using ES2017 async functions
The Simple, Secure Framework Developers Trust
The API and real-time application framework
Connect is a middleware layer for Node.js
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot