What is Fastify, and how does it compare to Express?
— Updated — Backend, Node.js, Fastify — 2 min read
Fastify is a web framework for Node.js built to handle a lot of requests with little overhead. If you've used Express, most of it will feel familiar. This post covers what Fastify is, how it compares with Express, and how to start a first server.
What is Fastify?
In Fastify's own benchmarks it serves more requests per second than Express and other popular Node.js frameworks. Keep in mind those are the project's own numbers on a "hello world" route. In a real app, your database and other calls usually take more time than the framework does.
A few things help it stay fast. Its router is built for quick route lookups. It uses JSON schemas you give it to validate requests and to serialize responses faster. It also supports HTTP/2 and streaming responses.
Most features live in plugins. You register the ones you need, like CORS, cookies or a database connection, and leave the rest out. Each plugin gets its own scope, so one plugin's settings don't leak into another part of the app.
Why use Fastify?
-
Performance. It spends less time per request than Express. That matters most when you serve a lot of traffic on a small number of servers.
-
Plugins. You add features with
fastify.register()instead of changing the core. This keeps a large app split into small, separate pieces. -
Developer experience. Route handlers can be
asyncfunctions that just return a value. Logging (with Pino) and request validation are built in, and the documentation is good. -
Community. There are official and community plugins for most common needs, listed in the Fastify ecosystem page.
Getting started with Fastify
The current version, Fastify v5, needs Node.js 20 or newer.
- Install Node.js if you haven't already.
- Create a new Node.js project.
- Install Fastify with npm:
npm install fastify
Create a new Fastify instance
const fastify = require('fastify')({ logger: true })
fastify.get('/', async (request, reply) => {
return { hello: 'world' }
})
fastify.listen({ port: 3000 }, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
console.log(`Server listening on ${address}`)
})Note that listen() takes an options object like { port: 3000 }. Older examples call fastify.listen(3000), but Fastify v5 removed that form.
Server in Express
// Express
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () => {
console.log('Express app listening on port 3000!')
})The two look alike. The main difference is in the route handler. In Fastify, an async handler can just return an object, and Fastify turns it into a JSON response. In Express you call res.send() or res.json() yourself.
If you're used to Express, Fastify takes a little getting used to, mostly the plugin system and the schemas. For a new Node.js API where speed matters, I think it's worth trying.