Fastify
Fastify is a highly performant, low-overhead web framework for Node.js, designed for speed and efficiency. It's great for building APIs due to its fast routing, built-in validation, and extensibility.
Core Features
-
High Performance:
Fastify is optimized for speed and can handle thousands of requests per second. -
Schema-Based Validation:
JSON Schema validation ensures that request data is accurate and well-formed. -
Built-in Asynchronous Support:
Fastify uses async/await, providing smooth handling of asynchronous operations. -
Plugin Architecture:
Fastify encourages modular development with its powerful plugin system.
Basic Setup
-
Installation:
npm install fastify
-
Hello World Example:
const fastify = require("fastify")({ logger: true });
fastify.get("/", async (request, reply) => {
return { message: "Hello, Fastify!" };
});
fastify.listen({ port: 3000 }, (err, address) => {
if (err) {
fastify.log.error(err);
process.exit(1);
}
fastify.log.info(`Server listening at ${address}`);
});
Routing
Fastify routes define the method, URL, and handler for processing requests.
-
Basic Route:
fastify.get("/hello", async (request, reply) => {
return { greeting: "Hello, Fastify!" };
}); -
Dynamic Routes:
fastify.get("/user/:id", async (request, reply) => {
const { id } = request.params;
return { userId: id };
}); -
Query Parameters:
fastify.get("/search", async (request, reply) => {
const { q } = request.query;
return { query: q };
}); -
Post Request with Body:
fastify.post("/data", async (request, reply) => {
const { name, age } = request.body;
return { received: { name, age } };
});
Schema Validation
Fastify uses JSON Schema for validating requests.
-
Request Body Validation:
fastify.post(
"/register",
{
schema: {
body: {
type: "object",
required: ["username", "password"],
properties: {
username: { type: "string" },
password: { type: "string", minLength: 6 },
},
},
},
},
async (request, reply) => {
return { message: "User registered successfully" };
}
); -
Query and Params Validation:
fastify.get(
"/products/:id",
{
schema: {
params: {
type: "object",
properties: {
id: { type: "string" },
},
},
querystring: {
type: "object",
properties: {
sort: { type: "string" },
},
},
},
},
async (request, reply) => {
return { productId: request.params.id, sort: request.query.sort };
}
);
Middleware and Plugins
Fastify uses hooks and plugins instead of middleware.
-
Hooks for Pre-Processing Requests:
fastify.addHook("onRequest", async (request, reply) => {
console.log(`Request received: ${request.method} ${request.url}`);
}); -
Creating and Registering Plugins:
async function examplePlugin(fastify, options) {
fastify.decorate("utility", () => "Utility Function");
fastify.get("/use-utility", async (request, reply) => {
return { message: fastify.utility() };
});
}
fastify.register(examplePlugin);
Error Handling
-
Global Error Handler:
fastify.setErrorHandler((error, request, reply) => {
fastify.log.error(error);
reply.status(500).send({ error: "Internal Server Error" });
}); -
Custom 404 Handler:
fastify.setNotFoundHandler((request, reply) => {
reply.status(404).send({ error: "Route Not Found" });
});
Serving Static Files
-
Install
fastify-static
Plugin:npm install fastify-static
-
Serve Static Files:
const path = require("path");
fastify.register(require("fastify-static"), {
root: path.join(__dirname, "public"),
prefix: "/public/",
});
Key Fastify Methods Cheat Sheet
Method | Description |
---|---|
fastify.get() | Define a GET route |
fastify.post() | Define a POST route |
fastify.addHook() | Add lifecycle hooks |
fastify.register() | Register a plugin |
fastify.decorate() | Add custom properties to Fastify |
fastify.setErrorHandler() | Set a global error handler |
fastify.listen() | Start the Fastify server |
-
Start with Simple Routes:
Build basic GET and POST routes to understand Fastify’s structure. -
Use Schema Validation Early:
Fastify’s validation is fast and prevents common API errors. -
Leverage Plugins:
Use official plugins likefastify-static
,fastify-cors
, andfastify-formbody
for common needs. -
Check the Official Documentation:
Visit the Fastify Docs for in-depth explanations and examples.