Consider taking a step back and viewing express as a middleware stack, much like a literal stack.
With a series of app.use
, app.get
, and app.post
calls, you create a chain of middleware functions. When a request is received, express identifies which middleware functions match the URL pattern and calls the first one, passing along a reference to the next in line. This is how separate, independent middleware objects become interconnected.
For instance, there are middleware functions that parse query strings into an object stored in req.query
, handle cookie header parsing, and provide access logging. These functions are linked together in a cohesive chain, with each passing control to the next by invoking next()
.
app.use(express.logger());
app.use(express.responseTime());
app.use(express.compress());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.cookieParser());
app.use(express.session());
app.use(i18n.handle);
app.use(app.router);
The reason routes typically don't use next
is because they often mark the end of a middleware chain. After reaching a route, there's usually no further processing needed.