The Request Pipeline — Every Express App's Backbone
Middleware Intro
Middleware is the chain of functions every request flows through. Master it and you've mastered Express.
What you'll learn
- Understand the (req, res, next) signature
- Recognize the four kinds of middleware
- See the pipeline as data flow
A middleware is a function (req, res, next) => { ... }. Express
calls them in order. Each one either:
- Responds — sends a response, ending the chain
- Passes — calls
next()to invoke the next middleware - Errors — calls
next(err)to skip to error middleware
That’s the whole model.
Visualizing the Pipeline
Request → logger → bodyParser → auth → route handler → Response
↓ next ↓ next ↓ next ↓ res.send
Every Express feature — JSON parsing, sessions, auth, CORS, compression — is implemented as middleware. So is your business logic.
Four Kinds
| Kind | Mount | Use For |
|---|---|---|
| Application | app.use(fn) | Site-wide (logging, body parsing) |
| Router | router.use(fn) | Per-router (auth on /api/*) |
| Route | app.get(path, fn1, fn2, handler) | Specific to a route |
| Error | app.use((err, req, res, next) => ...) | 4-arg signature |
A Tiny Example
import express from "express";
const app = express();
// 1. application middleware
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
// 2. parses JSON bodies
app.use(express.json());
// 3. route — also a middleware
app.get("/", (req, res) => {
res.send("hello");
});
app.listen(3000); When a request hits /, the logger logs, JSON parser does nothing
(no body on GET), then the route sends the response.
Why Order Matters
Middleware runs in the order you mount it. Mount the JSON
parser before routes that need req.body. Mount error middleware
last. Mount static middleware before catch-all 404s.
The Express Mental Model
Once you internalize “request flows down the chain, response flows back up,” everything in Express makes sense. Auth? Add middleware before routes. Logging? Add middleware first. CORS? Middleware. Compression? Middleware. Sessions? Middleware. Rate limiting? Middleware.
Frameworks like Koa and Hono use the same model, with slightly different signatures. Once you get Express middleware, you get them all.
Authoring Middleware →