As for a simple example, in this two sample code here, how is a next() a parameter and how can
it be executed to automatically go to the next middleware function? How does this work behind the abstraction?
app.use((req, res, next) => {
console.log('Time:', Date.now())
next()
});
app.use((req, res, next) => {
console.log('Time2:', Date.now())
next()
});
This outputs:
Time: (Now’s date)
Time2: (Now’s date)
This is done from top to bottom.
2
Answers
next
will be a closure that contains a reference to the array of middlewares and the current index (or some equivalent data). So when you call it, it increments the index and calls that middleware’s function. Each call tonext()
steps through all the middlewares until it gets to the end.Not necessarily. What happens is that
app.use()
collects the middlewares in an array. Then when a request comes in, the router goes through that array and can create the respectivenext
callback for each middleware so that it will run the remaining handlers. The router also selects the middlewares according to path, method, etc if you have restricted them – which you didn’t in your example.Here’s a small demo: