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.