DEV Community

Alex Spinov
Alex Spinov

Posted on

Fastify Has a Free API — Here's How to Build High-Performance REST APIs

Fastify is one of the fastest web frameworks for Node.js. It provides schema-based validation, plugin architecture, and TypeScript support — processing 30K+ requests/second.

Installation

npm install fastify
Enter fullscreen mode Exit fullscreen mode

Basic Server

import Fastify from "fastify";

const app = Fastify({ logger: true });

app.get("/", async () => {
  return { message: "Hello from Fastify!" };
});

app.get("/users/:id", async (request) => {
  const { id } = request.params;
  return { id, name: "User " + id };
});

await app.listen({ port: 3000 });
Enter fullscreen mode Exit fullscreen mode

Schema Validation

const postSchema = {
  body: {
    type: "object",
    required: ["title", "content"],
    properties: {
      title: { type: "string", minLength: 1, maxLength: 200 },
      content: { type: "string" },
      tags: { type: "array", items: { type: "string" } }
    }
  },
  response: {
    201: {
      type: "object",
      properties: {
        id: { type: "number" },
        title: { type: "string" },
        createdAt: { type: "string" }
      }
    }
  }
};

app.post("/posts", { schema: postSchema }, async (request, reply) => {
  const post = await db.createPost(request.body);
  reply.code(201).send(post);
});
Enter fullscreen mode Exit fullscreen mode

Plugins

// Database plugin
async function dbPlugin(fastify) {
  const pool = createPool(process.env.DATABASE_URL);
  fastify.decorate("db", pool);
  fastify.addHook("onClose", async () => pool.end());
}

app.register(dbPlugin);

// Auth plugin with prefix
async function authRoutes(fastify) {
  fastify.post("/login", async (req) => { /* ... */ });
  fastify.post("/register", async (req) => { /* ... */ });
}

app.register(authRoutes, { prefix: "/auth" });
Enter fullscreen mode Exit fullscreen mode

Hooks

app.addHook("onRequest", async (request) => {
  request.startTime = Date.now();
});

app.addHook("onResponse", async (request, reply) => {
  const duration = Date.now() - request.startTime;
  request.log.info(`${request.method} ${request.url}${duration}ms`);
});

// Auth hook
app.addHook("preHandler", async (request, reply) => {
  const token = request.headers.authorization?.replace("Bearer ", "");
  if (!token) reply.code(401).send({ error: "Unauthorized" });
  request.user = verifyToken(token);
});
Enter fullscreen mode Exit fullscreen mode

Need to extract or automate web content at scale? Check out my web scraping tools on Apify — no coding required. Or email me at spinov001@gmail.com for custom solutions.

Top comments (0)