Skip to content
Tutorials Center
My learning

Topics

Lesson 2 of 43 ยท Getting Started

Express vs Fastify, Koa, NestJS and Hapi

Compare Express with Fastify, Koa, NestJS and Hapi: design ideas, speed, ecosystem, enterprise and microservice fit, and a clear guide to choosing the right Node.js framework.

Express is the best-known Node.js web framework, but it is not the only one, and it is not always the best fit. Newer frameworks were built to fix specific pains: speed, structure, validation, async handling. If you are starting a project, joining a team that uses one of them, or answering an interview question like "why Express and not Fastify?", you need a clear picture of the alternatives.

This lesson compares the four you will hear about most: Fastify, Koa, NestJS and Hapi. It does not declare a winner, because there isn't one. Instead you will learn what each framework is for, see two of their key ideas working in small runnable stand-ins, and finish with a decision guide. The frameworks themselves cannot be installed on this site, so the real code is read-only.

Five frameworks, five priorities

Express Minimal, familiar, huge ecosystem.
Fastify Speed and schema validation.
Koa Async middleware, tiny core.
NestJS Structure for big teams.
1 / 2

A quick reminder: what Express is

Express (2010) is a thin layer on top of Node's http module: routing, a middleware chain, request and response helpers. Everything else (validation, database access, authentication) is a package you add. That openness explains both its popularity (a huge ecosystem, countless tutorials and Stack Overflow answers, every Node developer knows it) and its limits (no enforced structure, no built-in validation, performance that is "good enough" rather than best in class). See What is Express? for the basics.

Express 5, the current major version, closed an important gap: rejected promises in async handlers now reach your error middleware automatically.

Fastify

Fastify (2016) is designed around two ideas: speed and schemas. You describe the shape of requests and responses with JSON Schema; Fastify validates input with it and uses it to compile a very fast serializer for output. It also has a plugin system with encapsulation (a plugin's decorators and hooks stay local unless you share them) and a built-in logger (Pino).

JavaScript
// Read-only: needs the fastify package
import Fastify from 'fastify';

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

app.get('/users/:id', {
  schema: {
    params: { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
    response: { 200: { type: 'object', properties: { id: { type: 'integer' }, name: { type: 'string' } } } },
  },
}, async (request) => {
  return { id: request.params.id, name: 'Ada', passwordHash: 'never leaves' }; // extra field is dropped
});

await app.listen({ port: 3000 });
  • Strengths: among the fastest Node frameworks, validation and serialization built in, first-class TypeScript support, automatic request logging, JSON-first design, async/await everywhere, and OpenAPI documentation from the same schemas.
  • Costs: a smaller ecosystem than Express (although many Express middleware have Fastify counterparts), and a plugin model that takes a little time to understand.

Koa

Koa (2013) comes from the original Express team. It keeps the core tiny (no router, no body parser: you add them) and embraces async/await with a different middleware model. Instead of (req, res, next), a Koa middleware receives one context object (ctx) and a next() function that returns a promise. Code before await next() runs on the way in, code after it on the way out, which gives a clean "onion".

JavaScript
// Read-only: needs the koa package
import Koa from 'koa';

const app = new Koa();

app.use(async (ctx, next) => {
  const start = Date.now();
  await next();                                   // run everything downstream
  ctx.set('X-Response-Time', `${Date.now() - start}ms`);   // then continue here
});

app.use(async (ctx) => {
  ctx.body = { hello: 'world' };
});

app.listen(3000);
  • Strengths: small and elegant, great error handling (try { await next() }), a natural place to measure or wrap downstream work.
  • Costs: you assemble more yourself, the ecosystem is smaller, and since Express 5 handles async errors too, Koa's biggest advantage has narrowed.

The onion, run live

The onion is the best-known difference between the two. The first example builds the core of both models in a few lines. The Koa one is the real algorithm of koa-compose in spirit: each middleware gets a next that calls the following one and returns its promise.

Node.js Express chain vs Koa onion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In Express's callback style, next() returns immediately: "A after next() returned" prints before the asynchronous work in B finishes, so a timing or cleanup middleware cannot easily wait for the downstream result. In Koa's style the code after await next() runs only after everything downstream, including async work, completes. That makes wrapping logic (timing, transactions, error handling) very natural. (Express can do similar things by listening to the response's finish event, as in Logging and Debugging.)

NestJS

NestJS (2017) is not an alternative to Express so much as a framework on top of it. By default Nest runs on Express (or optionally Fastify) and adds the thing Express deliberately lacks: architecture. It is written in TypeScript and borrows ideas from Angular and Spring: modules, controllers, providers with dependency injection, decorators, pipes for validation, guards for authorization, interceptors and a CLI that generates all of it.

TypeScript
// Read-only: needs @nestjs/common
@Controller('users')
export class UsersController {
  constructor(private readonly users: UsersService) {}   // injected

  @Get(':id')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.users.findOne(id);
  }
}
  • Strengths: consistent structure for big codebases and teams, built-in dependency injection, excellent TypeScript support, first-class patterns for microservices (message brokers, gRPC, GraphQL), testing utilities.
  • Costs: a steeper learning curve (decorators, DI, modules), more boilerplate for small services, and a heavier mental model. Overkill for a ten-route API.

Hapi

Hapi (2011, born at Walmart Labs to run Black Friday traffic) prefers configuration over code. Routes are objects, validation is built in through the Joi library, and the framework ships with caching, authentication strategies, and strong security defaults. It deliberately avoids depending on community middleware.

JavaScript
// Read-only: needs @hapi/hapi and joi
server.route({
  method: 'GET',
  path: '/users/{id}',
  options: { validate: { params: Joi.object({ id: Joi.number().integer().required() }) } },
  handler: (request) => ({ id: request.params.id }),
});
  • Strengths: built-in validation, authentication, caching, lifecycle control and a stable, security-minded core.
  • Costs: smaller community, its own conventions (routes use not :id), and little enthusiasm for new projects compared with Fastify or Nest.

Schema-first routes, run live

Fastify's key idea is that the route declares its contract and the framework enforces it. The next stand-in implements that idea in about 40 lines. It is not Fastify, and it validates far less than JSON Schema does, but it shows why this approach removes boilerplate and protects responses.

Node.js A schema-first route (Fastify idea, simplified)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The handler returned a passwordHash, but the response schema listed only id and name, so the leak never reached the client. Invalid ids were rejected with 400 before the handler ran. With Express you would write both behaviors yourself or add libraries (see Validation and Security Best Practices).

Side by side

Express Fastify Koa NestJS Hapi
First release 2010 2016 2013 2017 2011
Philosophy Minimal, unopinionated Fast, schema-driven Tiny core, async onion Opinionated architecture Configuration, built-in features
Middleware style (req, res, next) Hooks and plugins async (ctx, next) Guards, pipes, interceptors (on Express/Fastify) Lifecycle extensions, plugins
Validation built in No (add Zod, Joi, ...) Yes (JSON Schema) No Via pipes (class-validator, Zod) Yes (Joi)
TypeScript Types via @types First class Types via @types Required, first class First class
Raw speed Good Very high High Depends on the adapter Moderate
Ecosystem Largest Large, growing Medium Large (Nest ecosystem) Medium
Learning curve Gentle Moderate Gentle Steep Moderate

Benchmarks vary with the test, but the ordering is consistent: Fastify handles noticeably more simple requests per second than Express, and the gap shrinks to almost nothing once real work (database calls, JSON processing, authentication) dominates the time. Choosing a framework for raw speed alone is rarely the right decision.

Enterprise use and microservices

  • Enterprise teams value consistency and onboarding speed. NestJS is popular here because every service looks the same (modules, controllers, providers) and because its patterns feel familiar to developers coming from Spring or .NET.
  • Express remains common in large organizations, often with an internal template that fixes the structure, logging, validation and error format. Its biggest asset is that finding developers and libraries is easy.
  • Microservices need small, fast-starting, well-observed services. Fastify fits well (low overhead, schemas, structured logs); Express is perfectly capable with lean middleware; Nest has dedicated microservice transports. The framework is less important than the practices around it: health checks, graceful shutdown, structured logs and contracts (Deployment, REST API Design).
  • Serverless functions favor frameworks with fast cold starts and small bundles, which gives Fastify, Koa or even no framework at all an edge.

How to choose

  • Learning Node, prototyping, or building a typical web app or API: Express. The skills transfer to everything else.
  • High-throughput JSON API, schema validation and OpenAPI wanted from the start: Fastify.
  • You like small, composable cores and async-first design: Koa.
  • Large team, long-lived codebase, TypeScript, strong conventions: NestJS.
  • Configuration-driven services with built-in authentication and validation: Hapi.
  • An existing codebase: keep its framework unless you have a measured reason to move. Rewrites rarely pay for themselves.

The good news is that the jump between them is small. Routing, middleware or hooks, request validation, error handling, and testing all appear in every framework. Building a solid Express foundation, as this course does, prepares you for each of them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Fastify use to validate requests and speed up response serialization?

    Fastify routes declare JSON Schema for params, query, body and responses, which it compiles into fast validators and serializers.
  2. 2. How does Koa's middleware differ from Express's (req, res, next)?

    next() returns a promise, so middleware can wrap everything downstream, forming an onion.
  3. 3. What is NestJS in relation to Express?

    Nest uses Express or Fastify as its HTTP layer and adds an architecture around it.
  4. 4. Which situation favors NestJS over plain Express?

    Nest's conventions pay off with team size and project lifetime, and are overkill for tiny services.
  5. 5. Why is raw benchmark speed rarely a good reason alone to switch frameworks?

    Once real work dominates, the difference between frameworks shrinks.

Summary

  • Express is minimal, familiar and has the biggest ecosystem; it is the right first framework and a fine production choice.
  • Fastify adds speed and schema-based validation and serialization; Koa offers a tiny core with an async "onion" middleware model; NestJS adds architecture and dependency injection on top of Express or Fastify; Hapi favors configuration and built-in features.
  • Speed differences matter least when database and business logic dominate.
  • Enterprise and microservice fit depends on conventions, team size and operations more than on the framework name.
  • Concepts (routing, middleware, validation, errors, testing) transfer between all of them, so Express skills are not wasted.

Next: build your first app in Your First Express App, or see how a generated project is laid out in The Express Generator and Project Scaffolding.