INSIGHTS
Software Development

Express vs Fastify: Routing, Validation and Performance Trade-Offs

In this article
  1. Express: a minimal JSON endpoint
  2. Fastify: a route with a JSON schema
  3. Compare the operational model, not only route syntax
  4. Test both with the same input contract
  5. Performance comparison must be reproducible

Express and Fastify are both Node.js frameworks for HTTP services, but they emphasize different defaults. Express has a lean middleware-oriented API and a mature extension ecosystem. Fastify focuses on plugin encapsulation and optional schema-driven validation and serialization. “Which is faster?” is not a useful decision until you describe your request workload, version, deployment topology and validation requirements.

Express: a minimal JSON endpoint

// Install: npm install express
const express = require("express");
const app = express();
app.use(express.json());

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

app.post("/echo", (req, res) => {
  const text = req.body?.text;
  if (typeof text !== "string" || !text.trim()) {
    return res.status(400).json({ error: "text required" });
  }
  res.status(201).json({ text: text.trim() });
});

app.listen(3000, () => console.log("Listening on 3000"));

Express routes map an HTTP method and path to a callback. The application registers JSON parsing middleware explicitly and performs a simple check before using the request body. In production, use an input schema library, centralized error handling, structured logging and appropriate size limits; do not assume the presence of express.json() is comprehensive validation.

Fastify: a route with a JSON schema

// Install: npm install fastify
const app = require("fastify")({ logger: true });

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

app.post("/echo", {
  schema: {
    body: {
      type: "object",
      required: ["text"],
      additionalProperties: false,
      properties: { text: { type: "string", minLength: 1 } }
    }
  }
}, async (request, reply) => {
  reply.code(201);
  return { text: request.body.text.trim() };
});

app.listen({ port: 3000 });

Fastify can validate incoming JSON against the route schema before invoking the handler. This sample rejects a missing or empty string but still permits whitespace-only text unless a separate rule is added; add a more specific application validation rule before promising that whitespace is disallowed. Schema definitions are trusted application code, not templates accepted from users. The official Fastify validation guide explains the model and warnings.

Compare the operational model, not only route syntax

  • Routing: Both map methods and paths to handlers; Express emphasizes middleware composition while Fastify also uses encapsulated plugins and hooks.
  • Validation: Express needs deliberate validation middleware or explicit checks; Fastify supports JSON Schema at the route level. Neither replaces business authorization.
  • Observability: Both can integrate request IDs, logs, metrics and distributed tracing. Inspect what your deployment already uses.
  • Ecosystem: Prefer proven adapters for your database, authentication and deployment platform over a framework chosen solely for a benchmark claim.

Test both with the same input contract

curl -i http://localhost:3000/health
curl -i -X POST http://localhost:3000/echo \
  -H "Content-Type: application/json" -d '{"text":"hello"}'
curl -i -X POST http://localhost:3000/echo \
  -H "Content-Type: application/json" -d '{}'

Run each server separately on port 3000. Both should return JSON for the valid calls and HTTP 400 for the missing text field, although their error-body shapes differ. Include malformed JSON, oversized bodies, asynchronous errors and authentication failures when designing real service acceptance tests.

Performance comparison must be reproducible

Framework-level microbenchmarks can differ substantially from a real application that waits on a database or external service. Compare equal Node.js versions, identical business logic, same serialization, same TLS and logging settings, and representative concurrency. Measure tail latency, errors and resource consumption as well as average throughput. A high request-per-second number in a hello-world demo is not a substitute for stability under production load.

For the exact Express route behavior, see Express routing documentation. The practical choice depends on maintainability, validation needs, team familiarity, plugins and measured workload behavior. Both are credible options; neither is universally superior for every Node.js API.

Filed under Software Development