Skip to content
Tutorials Center
My learning

Topics

Lesson 88 of 133 ยท Frameworks and Ecosystem

Express and Minimal Frameworks

Learn Express routing, middleware and error handling, run the same app on a hand-written mini-Express, compare Koa, Fastify and Hono, and choose a Node.js web framework with confidence.

The built-in node:http module is enough to write a server, as you saw in Building an HTTP Server and Routing. But once an app has a dozen routes, JSON bodies, authentication, logging and error handling, you find yourself writing the same plumbing over and over. A web framework packages that plumbing. Express is the oldest and most widely used one in the Node.js world: a thin layer on top of http that adds routing, a middleware chain and a few helpers for responses.

Our editor cannot install npm packages, so Express itself cannot run here. This lesson therefore does two things. It shows you real Express code (read-only, with what it would print on your machine), and it gives you a small mini-Express that implements the same API, so you can run an application written in Express style right now and see every request and response. Then we look at the frameworks that took different approaches, Koa, Fastify and Hono, and finish with advice on choosing one.

Why a framework at all

Here is a tiny API with plain node:http: list books, get one book, 404 for everything else. It runs, and it is perfectly fine for this size.

Node.js The same API with plain node:http

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.

Look at what you had to write yourself: URL parsing, a regular expression per route, a send helper, method checks, and a fallback. Add POST bodies, authentication, query strings, validation and error handling, and the single request handler becomes a long chain of if statements. Frameworks give that structure a name and a place:

  • Routing: declare GET /books/:id and receive req.params.id.
  • Middleware: small functions that run before your handler for logging, authentication or body parsing.
  • Error handling: one place that turns any failure into a proper response.
  • Helpers: res.status(201).json(data) instead of writeHead and JSON.stringify.

Express in five minutes

Express is installed with npm. The commands and code below are read-only here, because the editor has no npm packages. The API is small, and almost everything is one of three ideas: app.use for middleware, app.METHOD for routes, and req/res for the request and response.

Terminal
npm install express
JavaScript
import express from 'express';

const app = express();
app.use(express.json());                      // parse JSON request bodies

app.get('/books/:id', (req, res) => {
  const book = books.get(Number(req.params.id));
  if (!book) return res.status(404).json({ error: 'book not found' });
  res.json(book);
});

app.post('/books', (req, res) => {
  const book = { id: nextId++, title: req.body.title };
  books.set(book.id, book);
  res.status(201).json(book);
});

app.listen(3000, () => console.log('listening on http://localhost:3000'));
TEXT
$ curl -i http://localhost:3000/books/1
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8

{"id":1,"title":"Learning Node"}

That X-Powered-By: Express header tells attackers which framework you use. Turn it off with app.disable('x-powered-by'), or better, add the helmet package, which sets a whole group of safer security headers.

The pieces you need to know

Routing. app.get, app.post, app.put, app.patch, app.delete register a handler for a method and a path. Paths can have named parameters (/users/:id), and req.query holds the parsed query string (/search?q=node gives { q: 'node' }). Handlers run in the order they were registered, and the first one that sends a response ends the request.

Middleware. A middleware is a function (req, res, next). It can do some work, then either end the response or call next() to pass control on. Registration order is execution order: a logger placed after the routes would never see a matched request. The idea is explained in depth in Middleware Pattern.

Routers. express.Router() creates a mini-app you can mount under a prefix, which is how you split a big app into files: app.use('/books', booksRouter).

Error handling. A middleware with four parameters, (err, req, res, next), is an error handler. Express recognizes it by the parameter count. Any error that is thrown in a handler, or passed to next(err), skips ahead to the first error handler.

Express 5 and async handlers. Express 5, the current major version, treats a rejected promise returned by a handler like a thrown error and forwards it to the error handler. In Express 4 you had to wrap every async handler yourself (or install a helper package) or the request would hang and the process could crash with an unhandled rejection. If you maintain an Express 4 app, this is the biggest behavior change to know about when upgrading; Express 5 also tightened the route path syntax (wildcards must be named, like /*splat) and ships its own improvements to the query parser defaults.

JavaScript
// Express 5: the thrown error reaches the error handler without any wrapper
app.get('/report', async (req, res) => {
  const data = await loadReport();   // if this rejects, the error handler runs
  res.json(data);
});

app.use((err, req, res, next) => {
  console.error(err);
  res.status(err.status ?? 500).json({ error: err.message });
});

Other built-ins worth knowing: express.static('public') serves files from a folder, express.urlencoded({ extended: false }) parses HTML form posts, req.get('header-name') reads a header, and res.redirect, res.sendFile, res.download and res.cookie cover common responses. Behind a reverse proxy (nginx, Cloudflare, a load balancer) set app.set('trust proxy', 1) so req.ip and req.protocol reflect the real client instead of the proxy.

Running Express-style code here: a mini-Express

To make the ideas concrete, here is a small framework with the same API for the parts we just used: use, get, post, req.params, req.query, res.status().json(), error handlers with four parameters, and automatic forwarding of rejected promises. It is not a replacement for Express, but everything below the line "the application" is written exactly as it would be in Express. Only the first part is the framework. Read the top part to see how little magic there is, then follow the requests at the bottom.

Node.js mini-express: the Express API in about 70 lines

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.

Study the sequence of requests:

  1. GET /books/1 finds the route, fills req.params.id and answers 200.
  2. GET /books/7 is a normal "not found" decided by your own handler.
  3. The first POST passes through express.json(), which fills req.body, so a 201 comes back.
  4. The second POST has the wrong field name; the handler's validation returns 422.
  5. GET /crash has an async handler that rejects. The framework forwards the rejection to next(error), the four-parameter handler catches it and returns 500 with the message. Nobody wrapped anything in try/catch.
  6. GET /missing matches no route, falls through to the catch-all middleware and gets the JSON 404.

The logger at the end shows that the middleware ran for every request, including the failures, because it was registered before the routes. If you move the catch-all 404 above the routes, every request returns 404: order is everything. In real applications you also hide internal error messages from clients in production and log them on the server instead.

This mini version is simplified on purpose. Real Express adds sub-routers, app.all, optional parameters, content negotiation, ETags, req.ip, cookies, res.sendFile with range requests and much more, and it is far better tested. Use the mini-Express to learn, and the real one for real projects. A longer build of the same idea is in Middleware Pattern.

Routers, static files and the catch-all 404

Three features turn a single-file demo into an application: sub-routers, static files and a final "not found" handler. In real Express:

JavaScript
import express from 'express';
import path from 'node:path';

const app = express();
app.use(express.static(path.join(import.meta.dirname, 'public')));   // 1. files first

const books = express.Router();                                       // 2. a mini-app for /books
books.get('/', listBooks);
books.get('/:id', showBook);
books.post('/', express.json(), createBook);                          //    middleware for one route only
app.use('/books', books);                                             //    mount it under a prefix

app.use((req, res) => res.status(404).json({ error: 'no such route' })); // 3. last: nothing matched

A router is itself a middleware function. app.use('/books', books) strips the prefix before the router sees the request (inside, the path /books/42 looks like /42, and req.originalUrl keeps the full URL, while req.baseUrl is /books). That is why a router file does not need to know where it is mounted, and why one router can be mounted twice (for example under /v1 and /v2). Routes accept extra middleware before the handler (books.post('/', express.json(), createBook)), which is the right place for a body parser, an authorization check or a validator that only one route needs.

express.static(dir) looks for a file that matches the URL path. When it finds one it sends it, with the right Content-Type, ETag and Last-Modified headers, and does not call next(). When there is no file it calls next(), so the request continues to your routes. Two consequences: put it before the routes you want it to shadow (and after anything that must run first, such as a logger), and never point it at a folder that contains secrets, because everything inside is public. It also protects against ../ path traversal by refusing paths that leave the root, a bug people regularly create when they serve files by hand (see Paths and Permissions).

The same three ideas, running, in a miniature where the router and the static middleware are just functions of (req, res, next):

Node.js A router, static files and the final 404 as plain middleware

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.

Look at /books/2: the router answers with mountedAt: "/books" and innerUrl: "/2", which is exactly the prefix-stripping described above. The static layer served / and /app.css itself and passed everything else on, and the logger, registered first, recorded every request including the 404s. The final use is the catch-all: because it is last, it only runs for requests nothing else answered.

A different shape: Koa and the onion

Koa was created by the Express team to be smaller and to use async/await from the start. It has no router or body parser built in. Instead of (req, res, next), a Koa middleware is async (ctx, next), where ctx bundles the request and response and await next() runs the rest of the chain. Code after await next() runs on the way back out, which creates an "onion": each layer wraps the next. That is perfect for timing, error handling and anything that needs to see the response after the handler produced it.

The heart of Koa is a 15-line function that composes middleware. Here it is, with three layers:

Node.js Koa style: the onion in 15 lines

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.

Notice that for /boom the timing layer still logs "after, status 500": the error was converted into a response by the second layer, so the outer layer sees a normal return. Error handling in Koa is just a try/catch around await next().

Web-standard frameworks: Hono

The newest generation of frameworks, with Hono as the best known, is built on the web platform's Request and Response objects, the same ones fetch uses. A handler receives a Request and returns a Response (or a promise of one). Because those are standard, the same app can run on Node.js, Deno, Bun, Cloudflare Workers and other runtimes; for Node.js a small adapter package connects the HTTP server to the fetch function of your app.

You can see the idea without any package. This app has an app.fetch(request) method, routes matched with the built-in URLPattern, and it is tested by calling fetch directly with a Request: no server, no ports.

Node.js Hono style: Request in, Response out

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.

Testing without a socket is a real advantage of this style: tests are fast and need no free port. In real Hono the same app is const app = new Hono(); app.get('/hello/:name', (c) => c.json({...})), and the Node adapter starts it with serve({ fetch: app.fetch, port: 3000 }).

Fastify: speed and schemas

Fastify keeps the callback-style handler but adds a few ideas that matter at scale. It lets you attach a JSON Schema to each route: Fastify validates incoming data against it, serializes the response with a precompiled function (much faster than JSON.stringify for known shapes) and generates documentation from it. It has an encapsulated plugin system for organizing code, built-in structured logging with pino, and consistently strong benchmark results. The syntax looks like this (read-only):

JavaScript
import Fastify from 'fastify';

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

app.get('/books/:id', {
  schema: {
    params: { type: 'object', properties: { id: { type: 'integer' } }, required: ['id'] },
    response: { 200: { type: 'object', properties: { id: { type: 'integer' }, title: { type: 'string' } } } },
  },
}, async (request) => {
  return books.get(request.params.id);   // returning a value sends it as JSON
});

await app.listen({ port: 3000 });

Choosing a framework

There is no single best choice; there is a best choice for your constraints.

Express Koa Fastify Hono
Style (req, res, next) async (ctx, next) onion Handlers + plugins + schemas Request to Response
Built in Routing, static, JSON/form parsing Almost nothing Routing, validation, logging, hooks Routing, middleware, helpers
Ecosystem Largest by far Moderate Large, growing Growing fast
Runs on Node.js Node.js Node.js Node.js, Deno, Bun, edge runtimes
Good for Most apps, learning, huge community Minimalists, custom stacks High throughput, schema-first APIs Portable code, edge, tiny services

Practical guidance:

  • Learning or maintaining a typical app: Express. Almost every tutorial, middleware package and Stack Overflow answer assumes it.
  • Performance-sensitive JSON APIs: Fastify, especially when you want validation and documentation from schemas.
  • Code that must run outside Node.js or at the edge: Hono.
  • Large teams that want conventions, dependency injection and a prescribed structure: a full framework such as NestJS (built on top of Express or Fastify) or AdonisJS.
  • A tiny service or an internal tool: plain node:http plus a few helper functions is sometimes the best framework of all, and the code in this lesson shows how far that goes.

Whatever you choose, keep your business logic out of the framework's handlers. Put it in plain functions that take plain data, and let the handler do only HTTP translation. Then switching frameworks, or testing, is cheap. Project Structure and Architecture shows how to arrange this. Validate input at the edge too; the next lesson, Validating Input, covers that, and Web Application Security lists the headers and checks every public app needs.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does Express recognize an error-handling middleware?

    Express checks the function's parameter count. A four-argument function is treated as an error handler and is only called when an error occurred.
  2. 2. In Express, what decides which handler runs first?

    Layers run in registration order. This is why a catch-all 404 must be registered after the routes and a logger before them.
  3. 3. What changed for async handlers in Express 5?

    Express 5 treats a rejected promise like a thrown error. In Express 4 you needed your own wrapper or the request could hang.
  4. 4. What does code placed after await next() do in a Koa middleware?

    Koa middleware forms an onion: the part before await next() runs on the way in, the part after it on the way out, which makes timing and error handling easy.
  5. 5. Which advantage comes from frameworks built on standard Request and Response objects, like Hono?

    Because Request and Response are web standards, the app is portable across runtimes, and tests need no server or port.

Summary

  • A framework packages routing, middleware, error handling and response helpers on top of node:http; Express is the most common one.
  • In Express, app.use registers middleware, app.get/post/... register routes, order of registration is order of execution, and a four-parameter function is an error handler.
  • Express 5 forwards rejected promises from async handlers to the error handler; it also changed route path syntax.
  • Our mini-Express runs the same style of application in the editor, showing that the core is a loop over layers calling next().
  • Koa uses async (ctx, next) middleware that wraps the rest of the chain like an onion; Hono uses standard Request/Response and runs on many runtimes; Fastify adds schemas, plugins and speed.
  • Choose by need: Express for ecosystem, Fastify for schema-driven performance, Hono for portability, NestJS-style frameworks for large-team conventions.
  • Keep business logic in plain functions so the framework stays replaceable.

Next: Validating Input