Skip to main content

Web frameworks · Intermediate · 26 min

Build a schema-validated API with Fastify 5

By Padding · Updated 18 Nov 2026
Node.js 26 (node:26 image) · Fastify 5.12.8 · @fastify/swagger 9.9.5

You will build a small products API with Fastify 5.12 on Node.js 26 that validates requests and shapes responses with JSON Schema, keeps its database helper and auth hook in plugins, logs every request, publishes OpenAPI docs and has tests that never open a port.

On this page

Fastify is a Node.js web framework built around one idea: describe each route's input and output with JSON Schema, and let the framework do the work that follows. It validates requests against the schema before your handler runs, turns your return value into JSON with a serialiser compiled from the response schema, and can publish the same schemas as OpenAPI documentation. It also ships with a structured logger and a way to send fake requests into the app for tests.

You will build a small API for a market stall's product list. Anyone can read products. Adding or removing one needs an API key. The products live in SQLite through Node's built-in node:sqlite module, so there is no database server to install. Along the way you split the app into plugins and see how Fastify's encapsulation decides which parts of the app can see a decorator or a hook.

Prices are stored as whole numbers in the currency's minor unit (kobo, pesewas, cents) next to a three-letter currency code. Floating-point prices round badly, and a stall that sells in naira, cedis and shillings needs the code with every price.

Step 1 · Create the project and install Fastify

Make a throwaway project folder and write a package.json with exact versions, so the code below behaves the same next month. "type": "module" lets every file use import. The dev script restarts the server when a file changes and loads a .env file once you have one:

Bash
mkdir -p ~/fastify-demo
cd ~/fastify-demo
cat > package.json <<'JSON'
{
  "name": "fastify-demo",
  "private": true,
  "type": "module",
  "scripts": {
    "dev": "node --watch --env-file-if-exists=.env server.js",
    "start": "node --env-file-if-exists=.env server.js",
    "test": "node --test"
  },
  "dependencies": {
    "@fastify/swagger": "9.9.5",
    "@fastify/swagger-ui": "6.1.4",
    "fastify": "5.12.8",
    "fastify-plugin": "6.0.1"
  }
}
JSON
cat > .gitignore <<'TXT'
node_modules/
.env
shop.db
TXT
npm install --no-audit --no-fund

fastify-plugin is a small helper you use in a later step. The two @fastify/swagger packages generate and display the API documentation.

Check it worked

Bash
npm ls fastify

The output ends with fastify@5.12.8. If npm prints ERESOLVE or a peer dependency warning, check that the four versions match the file above.

Step 2 · Start a server and read its logs

Keep building the app separate from starting it. app.js exports a function that builds a Fastify instance and adds routes, but does not listen on a port. server.js calls it and listens. Tests in a later step call the same function and never touch the network:

Bash
cat > app.js <<'JS'
import Fastify from "fastify";

export async function buildApp(options = {}) {
  const app = Fastify({ logger: options.logger ?? false });

  app.get("/health", async () => ({ status: "ok" }));

  return app;
}
JS
cat > server.js <<'JS'
import { buildApp } from "./app.js";

const app = await buildApp({
  logger: { level: process.env.LOG_LEVEL ?? "info" },
  dbFile: process.env.DB_FILE ?? "shop.db",
  apiKey: process.env.API_KEY,
});

try {
  await app.listen({ port: Number(process.env.PORT ?? 3000), host: process.env.HOST ?? "127.0.0.1" });
} catch (err) {
  app.log.error(err);
  process.exitCode = 1;
}
JS

A handler returns a value and Fastify sends it as JSON. There is no res.json() to call. logger turns on Pino, the logger built into Fastify. It writes one JSON object per line, which log tools can search without parsing free text. host defaults to 127.0.0.1, so only your own machine can reach the API. Set HOST=0.0.0.0 when it runs behind a reverse proxy or inside Docker.

Start the server in a second terminal, from ~/fastify-demo, and leave it running. --watch restarts it each time you save a file:

Bash
npm run dev

Back in the first terminal, call the health route:

Bash
curl -s http://127.0.0.1:3000/health

Check it worked

curl prints {"status":"ok"}. The server terminal shows a line containing "msg":"Server listening at http://127.0.0.1:3000", then two lines for your request: incoming request and request completed. Both carry the same reqId, such as req-1, and the second has a responseTime in milliseconds. When many requests overlap, that id is how you pick out the lines for one of them.

Step 3 · Add a database helper with a plugin

In Fastify, almost everything is a plugin: an async function that receives an instance and adds routes, hooks or decorators to it. A decorator attaches a value to the instance, here app.db, so every handler can reach the database without importing it.

Plugins are encapsulated. Whatever a plugin adds is visible inside that plugin and its children, not to its parent or siblings. That is what you want for routes and hooks, but a database helper must be shared by the whole app. Wrapping the plugin in fastify-plugin tells Fastify to skip the encapsulation for this one, so app.db lands on the root instance.

Create plugins/db.js. It opens the SQLite file, creates the table, adds three products the first time, and decorates the instance with four functions. The onClose hook closes the database when the app shuts down:

Bash
mkdir -p plugins
cat > plugins/db.js <<'JS'
import { Database } from "node:sqlite";
import fp from "fastify-plugin";

async function dbPlugin(app, opts) {
  const sqlite = new Database(opts.file ?? ":memory:");
  sqlite.exec(`
    CREATE TABLE IF NOT EXISTS products (
      id INTEGER PRIMARY KEY,
      name TEXT NOT NULL,
      price_minor INTEGER NOT NULL,
      currency TEXT NOT NULL,
      supplier_note TEXT
    )
  `);

  const { n } = sqlite.prepare("SELECT count(*) AS n FROM products").get();
  if (n === 0) {
    const insert = sqlite.prepare(
      "INSERT INTO products (name, price_minor, currency, supplier_note) VALUES (?, ?, ?, ?)",
    );
    insert.run("Shea butter 250 g", 350000, "NGN", "Tamale co-op, pays on delivery");
    insert.run("Kente notebook", 4500, "GHS", "Kumasi bindery");
    insert.run("Beaded keyring", 60000, "KES", "Narok group, 30-day terms");
  }

  // Turn a database row into the shape the API uses.
  const toProduct = (row) => row && {
    id: row.id,
    name: row.name,
    priceMinor: row.price_minor,
    currency: row.currency,
    supplierNote: row.supplier_note,
  };

  app.decorate("db", {
    list(limit) {
      return sqlite.prepare("SELECT * FROM products ORDER BY id LIMIT ?").all(limit).map(toProduct);
    },
    get(id) {
      return toProduct(sqlite.prepare("SELECT * FROM products WHERE id = ?").get(id));
    },
    add({ name, priceMinor, currency, supplierNote }) {
      const result = sqlite
        .prepare("INSERT INTO products (name, price_minor, currency, supplier_note) VALUES (?, ?, ?, ?)")
        .run(name, priceMinor, currency, supplierNote ?? null);
      return this.get(Number(result.lastInsertRowid));
    },
    remove(id) {
      return sqlite.prepare("DELETE FROM products WHERE id = ?").run(id).changes > 0;
    },
  });

  app.addHook("onClose", async () => sqlite.close());
}

export default fp(dbPlugin, { name: "db", fastify: "5.x" });
JS

Every query uses ? placeholders, so values from requests never become part of the SQL text. supplierNote is internal: the stall owner wants it stored, but customers must never see it. The next step makes sure of that.

Register the plugin in app.js. Replace the file with this version:

Bash
cat > app.js <<'JS'
import Fastify from "fastify";
import dbPlugin from "./plugins/db.js";

export async function buildApp(options = {}) {
  const app = Fastify({ logger: options.logger ?? false });

  await app.register(dbPlugin, { file: options.dbFile });
  app.get("/health", async () => ({ status: "ok" }));

  return app;
}
JS

Check it worked

Build the app without starting a server, wait for every plugin to load with ready(), and ask it about the decorator. With no dbFile, the plugin uses an in-memory database:

Bash
node --input-type=module -e '
import { buildApp } from "./app.js";
const app = await buildApp();
await app.ready();
console.log(app.hasDecorator("db"), app.db.list(10).length);
await app.close();
'

It prints true 3. If it prints an error about fastify-plugin expecting a different Fastify version, check that package.json pins fastify at 5.12.8.

Step 4 · Validate requests and shape responses with JSON Schema

Each route can declare a schema with any of querystring, params, body, headers and response. Fastify compiles the input schemas with Ajv and rejects a request that does not match with a 400 before your handler runs. It compiles the response schema into a serialiser that writes only the properties the schema lists, which is faster than JSON.stringify and stops fields you forgot about from leaking.

Put the product shape in its own file. The $id lets routes refer to it as product#:

Bash
cat > schemas.js <<'JS'
export const productSchema = {
  $id: "product",
  type: "object",
  required: ["id", "name", "priceMinor", "currency"],
  properties: {
    id: { type: "integer" },
    name: { type: "string" },
    priceMinor: { type: "integer", description: "Price in minor units: kobo, pesewas, cents" },
    currency: { type: "string", pattern: "^[A-Z]{3}$" },
  },
};

export const idParams = {
  type: "object",
  required: ["id"],
  properties: { id: { type: "integer", minimum: 1 } },
};
JS

Now the read routes, in a plugin of their own. Registered with a /products prefix, the path "" becomes /products and "/:id" becomes /products/:id:

Bash
mkdir -p routes
cat > routes/product-reads.js <<'JS'
import { idParams } from "../schemas.js";

export default async function productReads(app) {
  app.get("", {
    schema: {
      tags: ["products"],
      querystring: {
        type: "object",
        properties: { limit: { type: "integer", minimum: 1, maximum: 50, default: 20 } },
      },
      response: { 200: { type: "array", items: { $ref: "product#" } } },
    },
  }, async (request) => app.db.list(request.query.limit));

  app.get("/:id", {
    schema: { tags: ["products"], params: idParams, response: { 200: { $ref: "product#" } } },
  }, async (request, reply) => {
    const found = app.db.get(request.params.id);
    if (!found) return reply.code(404).send({ message: `No product with id ${request.params.id}` });
    return found;
  });
}
JS
cat > app.js <<'JS'
import Fastify from "fastify";
import dbPlugin from "./plugins/db.js";
import { productSchema } from "./schemas.js";
import productReads from "./routes/product-reads.js";

export async function buildApp(options = {}) {
  const app = Fastify({ logger: options.logger ?? false });

  app.addSchema(productSchema);
  await app.register(dbPlugin, { file: options.dbFile });
  app.get("/health", async () => ({ status: "ok" }));
  await app.register(productReads, { prefix: "/products" });

  return app;
}
JS

Three details do a lot of work here. request.query.limit arrives as text in the URL, but the schema says integer, so Fastify converts it before your handler sees it. default: 20 fills it in when it is missing. And the handler returns whole database objects, supplierNote included, but the response schema does not list that field, so it is never sent.

Try a good request, then three bad ones:

Bash
curl -s "http://127.0.0.1:3000/products?limit=2"
echo
curl -s "http://127.0.0.1:3000/products?limit=500"
echo
curl -s "http://127.0.0.1:3000/products/abc"
echo
curl -s "http://127.0.0.1:3000/products/99"
echo

Check it worked

The first call returns two products with id, name, priceMinor and currency, and no supplierNote. The next two return status 400 with a message naming the problem: querystring/limit must be <= 50 and params/id must be integer. You wrote no code for either. The last returns your own {"message":"No product with id 99"} with status 404.

Step 5 · Protect writes with a hook in an encapsulated plugin

Hooks run at fixed points in a request's life. An onRequest hook runs first, before the body is even parsed, which makes it the cheapest place to turn away a caller without a key. Because of encapsulation, a hook added inside a plugin applies only to the routes in that plugin. Put the write routes in their own plugin with the hook, and the read routes stay public without any if statements.

Create a key in a .env file. The file is created private before anything is written to it, and the key never appears on a command line:

Bash
( umask 077; node -e 'console.log("API_KEY=" + require("node:crypto").randomBytes(24).toString("hex"))' > .env )
ls -l .env

.gitignore already lists .env. On a server, put the key in the service's environment file instead and keep it out of version control.

Now the write routes. The body schema sets additionalProperties: false, and the routes declare security so the documentation in the next step shows which ones need the key:

Bash
cat > routes/product-writes.js <<'JS'
import { timingSafeEqual } from "node:crypto";
import { idParams } from "../schemas.js";

export default async function productWrites(app, opts) {
  const expected = Buffer.from(opts.apiKey ?? "");

  app.addHook("onRequest", async (request, reply) => {
    const sent = Buffer.from(request.headers["x-api-key"] ?? "");
    const valid = expected.length > 0 && sent.length === expected.length && timingSafeEqual(sent, expected);
    if (!valid) {
      request.log.warn("write rejected: missing or wrong API key");
      return reply.code(401).send({ message: "Send a valid x-api-key header" });
    }
  });

  app.post("", {
    schema: {
      tags: ["products"],
      security: [{ apiKey: [] }],
      body: {
        type: "object",
        required: ["name", "priceMinor", "currency"],
        properties: {
          name: { type: "string", minLength: 1, maxLength: 120 },
          priceMinor: { type: "integer", minimum: 0 },
          currency: { type: "string", pattern: "^[A-Z]{3}$" },
          supplierNote: { type: "string", maxLength: 500 },
        },
        additionalProperties: false,
      },
      response: { 201: { $ref: "product#" } },
    },
  }, async (request, reply) => {
    const created = app.db.add(request.body);
    request.log.info({ productId: created.id }, "product added");
    return reply.code(201).header("location", `/products/${created.id}`).send(created);
  });

  app.delete("/:id", {
    schema: { tags: ["products"], security: [{ apiKey: [] }], params: idParams },
  }, async (request, reply) => {
    if (!app.db.remove(request.params.id)) {
      return reply.code(404).send({ message: `No product with id ${request.params.id}` });
    }
    return reply.code(204).send();
  });
}
JS
cat > app.js <<'JS'
import Fastify from "fastify";
import dbPlugin from "./plugins/db.js";
import { productSchema } from "./schemas.js";
import productReads from "./routes/product-reads.js";
import productWrites from "./routes/product-writes.js";

export async function buildApp(options = {}) {
  const app = Fastify({ logger: options.logger ?? false });

  app.addSchema(productSchema);
  await app.register(dbPlugin, { file: options.dbFile });
  app.get("/health", async () => ({ status: "ok" }));
  await app.register(productReads, { prefix: "/products" });
  await app.register(productWrites, { prefix: "/products", apiKey: options.apiKey });

  return app;
}
JS

timingSafeEqual compares the keys in a time that does not depend on how many characters match, so the response time gives nothing away. If API_KEY is not set, expected is empty and every write is refused, rather than every write being allowed.

--watch restarts on code changes but reads .env only at start-up, so stop the server in the second terminal with Ctrl+C and start it again:

Bash
npm run dev

Try a write without the key, then with it. sed turns the line in .env into a header that curl reads from a file, so the key stays out of your shell history. The second request also sends a colour the schema does not know and a price written as a string:

Bash
curl -s -X POST http://127.0.0.1:3000/products \
  -H 'content-type: application/json' \
  -d '{"name":"Zobo mix 500 g","priceMinor":120000,"currency":"NGN"}'
echo
curl -s -i -X POST http://127.0.0.1:3000/products \
  -H @<(sed 's/^API_KEY=/x-api-key: /' .env) \
  -H 'content-type: application/json' \
  -d '{"name":"Zobo mix 500 g","priceMinor":"120000","currency":"NGN","colour":"red"}'
echo
curl -s "http://127.0.0.1:3000/products/4"
echo

Check it worked

The first request gets {"message":"Send a valid x-api-key header"} with status 401, and the server log shows a "level":40 line with write rejected. The second gets HTTP/1.1 201 Created, a location: /products/4 header and the new product. The GET reads it back with "priceMinor":120000 as a number and no colour, and GET /products still works with no key at all.

Two default settings explain that result. Fastify configures Ajv to convert types where it can, so "120000" became 120000, and to remove unknown properties when a schema sets additionalProperties: false, rather than reject the request. If you would rather refuse unknown fields with a 400, pass ajv: { customOptions: { removeAdditional: false } } to Fastify(). Leave out name and you get body must have required property 'name'.

Step 6 · Publish OpenAPI documentation

@fastify/swagger collects the schemas from every route and builds an OpenAPI document from them. @fastify/swagger-ui serves an interactive page for it. Swagger only sees routes registered after it, so it goes first. This is the final app.js:

Bash
cat > app.js <<'JS'
import Fastify from "fastify";
import swagger from "@fastify/swagger";
import swaggerUi from "@fastify/swagger-ui";
import dbPlugin from "./plugins/db.js";
import { productSchema } from "./schemas.js";
import productReads from "./routes/product-reads.js";
import productWrites from "./routes/product-writes.js";

export async function buildApp(options = {}) {
  const app = Fastify({ logger: options.logger ?? false });

  await app.register(swagger, {
    openapi: {
      info: { title: "Market stall API", version: "1.0.0" },
      components: {
        securitySchemes: { apiKey: { type: "apiKey", in: "header", name: "x-api-key" } },
      },
    },
  });
  await app.register(swaggerUi, { routePrefix: "/docs" });

  app.addSchema(productSchema);
  await app.register(dbPlugin, { file: options.dbFile });
  app.get("/health", async () => ({ status: "ok" }));
  await app.register(productReads, { prefix: "/products" });
  await app.register(productWrites, { prefix: "/products", apiKey: options.apiKey });

  return app;
}
JS

Fetch the generated document and print its OpenAPI version and paths:

Bash
curl -s http://127.0.0.1:3000/docs/json | node -p 'const d = JSON.parse(require("node:fs").readFileSync(0, "utf8")); d.openapi + " " + Object.keys(d.paths).join(" ")'

Check it worked

The command prints 3.0.3 /health /products /products/{id}. Open http://127.0.0.1:3000/docs in a browser: the page is titled Market stall API and lists five operations, with a padlock on POST and DELETE. The limits you wrote for validation, such as maximum: 50 and the currency pattern, appear in the documentation too, because they are the same schemas. To try a write from the page, choose Authorize and paste the key from .env.

The plugin writes OpenAPI 3.0.3 by default. If other tools need a later version, Describe an API with an OpenAPI 3.2 document covers what changed.

Step 7 · Test the API with inject

app.inject() sends a fake HTTP request straight into the app and returns the response. Hooks, validation and serialisation all run, but no port is opened, so tests are fast and can run side by side. Each test builds its own app with an in-memory database and a test key, and closes it afterwards:

Bash
mkdir -p test
cat > test/products.test.js <<'JS'
import { test } from "node:test";
import assert from "node:assert/strict";
import { buildApp } from "../app.js";

const apiKey = "test-key-for-inject-only";

async function setup(t) {
  const app = await buildApp({ apiKey, dbFile: ":memory:" });
  t.after(() => app.close());
  return app;
}

test("lists products without the supplier note", async (t) => {
  const app = await setup(t);
  const res = await app.inject({ method: "GET", url: "/products?limit=2" });
  assert.equal(res.statusCode, 200);
  const body = res.json();
  assert.equal(body.length, 2);
  assert.equal(body[0].supplierNote, undefined);
});

test("rejects a limit above 50", async (t) => {
  const app = await setup(t);
  const res = await app.inject({ method: "GET", url: "/products?limit=500" });
  assert.equal(res.statusCode, 400);
  assert.match(res.json().message, /must be <= 50/);
});

test("refuses a write without the API key", async (t) => {
  const app = await setup(t);
  const res = await app.inject({
    method: "POST",
    url: "/products",
    payload: { name: "Zobo mix 500 g", priceMinor: 120000, currency: "NGN" },
  });
  assert.equal(res.statusCode, 401);
});

test("creates, reads and deletes a product", async (t) => {
  const app = await setup(t);
  const created = await app.inject({
    method: "POST",
    url: "/products",
    headers: { "x-api-key": apiKey },
    payload: { name: "Zobo mix 500 g", priceMinor: 120000, currency: "NGN" },
  });
  assert.equal(created.statusCode, 201);
  const { id } = created.json();
  assert.equal(created.headers.location, `/products/${id}`);

  const read = await app.inject({ method: "GET", url: `/products/${id}` });
  assert.equal(read.json().name, "Zobo mix 500 g");

  const removed = await app.inject({
    method: "DELETE",
    url: `/products/${id}`,
    headers: { "x-api-key": apiKey },
  });
  assert.equal(removed.statusCode, 204);
});
JS
npm test

The test key is a fixed string because it only ever exists inside the test process. The real key stays in .env, which the tests never read.

Check it worked

npm test lists four passing tests and ends with pass 4 and fail 0. The dev server can keep running while the tests run, because they do not need port 3000. To see a failure, change maximum: 50 to maximum: 1000 in routes/product-reads.js and run npm test again; the second test fails. Change it back.

Step 8 · Clean up

Stop the dev server with Ctrl+C in the second terminal. Then remove the project, which also removes .env, the key in it and the shop.db database:

Bash
cd ~
rm -rf ~/fastify-demo

Check it worked

ls ~/fastify-demo reports that there is no such file or directory, and curl -s http://127.0.0.1:3000/health prints nothing because the server is gone.

Next steps

You now have the things Fastify gives you that Express 5 leaves to extra packages: input validation and type conversion from JSON Schema, response serialisation that drops unlisted fields, plugins with encapsulation so hooks and decorators apply only where you register them, a structured logger with request ids, OpenAPI documents built from the same schemas, and inject() for tests without a server. Compare it with the same kind of API in Build a REST API with Express 5.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.