Node.js theorytheory 0/50 · 0%
Web frameworks · medium

25. Structuring an Express-style API

Routes, middleware and the request/response pipeline.

Frameworks like Express model a server as a pipeline of middleware functions, each receiving `(req, res, next)`. Calling `next()` passes control to the next middleware; not calling it (after sending a response) ends the chain.

js
import express from "express";
const app = express();

app.use(express.json()); // parses JSON bodies into req.body

app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

app.get("/balances/:address", (req, res) => {
  res.json({ address: req.params.address, balance: "1000000000000000000" });
});

app.use((err, req, res, next) => { // error-handling middleware (4 args)
  res.status(500).json({ error: err.message });
});

app.listen(3000);

Middleware order matters: body parsers and logging generally go first, routes in the middle, and the error handler last, since Express only routes an error to a 4-argument middleware.

Check your understanding

  1. 1. What does calling next() inside middleware do?

  2. 2. How does Express distinguish an error-handling middleware?

  3. 3. Where should a JSON body-parsing middleware typically go?