Code Reference

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

APIRole
Fastify()Create instance
fastify.route / .getRegister routes
schemaValidate request + serialize response
replyResponse object (send, code)
listenBind host/port
Hook (examples)When
onRequestEarly request
preHandlerBefore handler
onSendBefore payload sent
onErrorError 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 async handlers or call reply.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.

On this page