While Express.js has been the go-to framework for years, Fastify has emerged as the performance champion for Node.js APIs. Here is how to build blazing-fast REST APIs with Fastify in 2026.
Why Fastify Over Express?
- 2x faster than Express in benchmarks
- Built-in JSON Schema validation
- Automatic Swagger documentation
- First-class TypeScript support
- Plugin-based architecture
Getting Started
npm init -y
npm install fastify @fastify/swagger @fastify/corsBasic Server Setup
import Fastify from "fastify";
const app = Fastify({ logger: true });
app.get("/api/health", async () => {
return { status: "ok", timestamp: Date.now() };
});
app.listen({ port: 3000, host: "0.0.0.0" });Schema Validation
const createUserSchema = {
body: {
type: "object",
required: ["name", "email"],
properties: {
name: { type: "string", minLength: 2 },
email: { type: "string", format: "email" },
role: { type: "string", enum: ["user", "admin"], default: "user" }
}
},
response: {
201: {
type: "object",
properties: {
id: { type: "string" },
name: { type: "string" },
email: { type: "string" }
}
}
}
};
app.post("/api/users", { schema: createUserSchema }, async (req, reply) => {
const user = await UserService.create(req.body);
reply.code(201).send(user);
});Plugin Architecture
// plugins/database.js
import fp from "fastify-plugin";
async function dbPlugin(fastify) {
const pool = createPool(process.env.DATABASE_URL);
fastify.decorate("db", pool);
fastify.addHook("onClose", () => pool.end());
}
export default fp(dbPlugin);Error Handling
app.setErrorHandler((error, request, reply) => {
request.log.error(error);
const statusCode = error.statusCode || 500;
reply.code(statusCode).send({
error: error.name,
message: statusCode === 500 ? "Internal Server Error" : error.message,
statusCode
});
});Rate Limiting
import rateLimit from "@fastify/rate-limit";
await app.register(rateLimit, {
max: 100,
timeWindow: "1 minute"
});Performance Tips
- Always define response schemas — Fastify uses them for fast serialization
- Use connection pooling for database connections
- Enable HTTP/2 for multiplexed connections
- Implement caching with Redis for frequently accessed data
Conclusion
Fastify gives you Express-like simplicity with significantly better performance. Its schema-first approach also improves API reliability and documentation. Start your next Node.js API project with Fastify.

Leave a Reply