Fastify Basics
Node.js · Reference cheat sheet
Fastify Basics
Node.js · Reference cheat sheet
📋 Overview
Fastify is a high-performance Node web framework focused on schemas, plugins, and low overhead. Validation and serialization are first-class via JSON Schema.
🔧 Core concepts
| API | Role |
|---|---|
Fastify() | Create instance |
fastify.route / .get | Register routes |
schema | Validate request + serialize response |
reply | Response object (send, code) |
listen | Bind host/port |
| Hook (examples) | When |
|---|---|
onRequest | Early request |
preHandler | Before handler |
onSend | Before payload sent |
onError | Error path |
💡 Examples
Minimal server:
import Fastify from "fastify";
const app = Fastify({ logger: true });
app.get("/", async () => ({ ok: true }));
await app.listen({ port: 9000, host: "0.0.0.0" });Schema validation:
app.post(
"/users",
{
schema: {
body: {
type: "object",
required: ["email"],
properties: { email: { type: "string", format: "email" } },
},
},
},
async (req, reply) => {
reply.code(201);
return req.body;
},
);Async handler errors:
app.get("/boom", async () => {
throw Object.assign(new Error("nope"), { statusCode: 400 });
});⚠️ Pitfalls
- Prefer
asynchandlers or callreply.send— don't mix both carelessly. - Validation errors return 400 by default; customize with
setErrorHandler. - Plugin encapsulation means decorations are not always global — register shared plugins at the right scope.