Middleware
The pipeline every request flows through - what middleware functions are, built-in middleware, third-party middleware, and writing your own.
What it is, in plain English: Middleware is a function with access to the request, response, and a 'next' function, that runs in the middle of the request-response cycle -- before your route handler. Middleware can run code, modify req/res, end the request, or call next() to pass control to the next middleware in the chain. This is THE core architectural pattern in Express -- logging, authentication, parsing request bodies, and error handling are all implemented as middleware.
The pipeline every request passes through
Middleware is the single most important concept in Express. Every piece of request processing -- parsing JSON bodies, checking authentication, logging, serving static files, handling errors -- is implemented as middleware.
The middleware function signature
function myMiddleware(req, res, next) {
// req -- the incoming request
// res -- the outgoing response
// next -- call this to pass control to the NEXT middleware in the chain
console.log("This runs for every request that reaches this middleware");
next(); // without calling next(), the request hangs forever!
}
app.use(myMiddleware); // applies to ALL routesThree things a middleware function can do
// 1. Run code and pass control onward:
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next(); // continue to the next middleware/route handler
});
// 2. End the request-response cycle:
app.use((req, res, next) => {
if (isMaintenanceMode) {
return res.status(503).send("Down for maintenance"); // no next() -- chain stops here
}
next();
});
// 3. Modify req or res before passing it on:
app.use((req, res, next) => {
req.requestTime = Date.now(); // add a custom property
next();
});
app.get("/", (req, res) => {
res.send(`Request received at ${req.requestTime}`); // can use it later
});Built-in middleware
// Parse JSON request bodies (without this, req.body is undefined for JSON requests):
app.use(express.json());
// Parse URL-encoded form bodies:
app.use(express.urlencoded({ extended: true }));
// Serve static files (CSS, images, client-side JS) from a folder:
app.use(express.static("public"));
// A request to /style.css automatically serves public/style.cssOrder matters
// Middleware runs in the EXACT order you register it:
app.use(express.json()); // 1. parse JSON first
app.use(logRequest); // 2. then log (can now log req.body too)
app.use("/api", apiRouter); // 3. then route to handlers
// If you registered logRequest BEFORE express.json(), req.body
// would still be undefined when the logger tried to use it.
Try It Yourself (Node.js logic)
Official Sources
- Express.js — Using Middleware
- Express.js — Writing Middleware
- Express.js — Error Handling
- helmet — npm package
The Codex links only to official documentation. No third-party tutorials.