What is middleware in Express and how the middleware stack works
middleware definition, req res next, middleware execution order, app.use, global vs route-level middleware, middleware chain, stack concept
The Express Middleware Stack
Middleware in Express is any function with the signature (req, res, next). When a request comes in, Express passes it through a stack of middleware functions in the order they were registered.
Each middleware can: read or modify req and res, end the request-response cycle, or call next() to pass control to the next function in the stack.
Basic middleware anatomy
function myMiddleware(req, res, next) {
console.log(`${req.method} ${req.url}`);
next(); // pass to next middleware or route
}
app.use(myMiddleware);Order matters
app.use(loggerMiddleware); // runs first
app.use(authMiddleware); // runs second
app.use(express.json()); // runs third
app.get('/data', routeHandler); // runs lastIf middleware does NOT call next() and does NOT send a response, the request hangs. If it sends a response without calling next(), the chain stops — this is how auth middleware blocks unauthorized requests.
Global middleware registered with app.use(fn) runs on every request. Route-level middleware is scoped to specific paths: app.use('/admin', adminAuth).
