IMHO, the accepted answer to this question is not very accurate. Others answered correctly, but I wanted to provide a little more code to make it more specific. Let's say you have this simple express application:
var express = require('express'); var app = express(); app.get('/user/:id', function (req, res, next) { console.log('before request handler'); next(); }); app.get('/user/:id', function (req, res, next) { console.log('handling request'); res.sendStatus(200); next(); }); app.get('/user/:id', function (req, res, next) { console.log('after request handler'); next(); }); app.listen(3000, function () { console.log('Example app listening on port 3000!') });
If you do
curl http:
you will see that this is printed on the console:
before request handler handling request after request handler
Now, if you comment on the next() call in the middle handler as follows:
app.get('/user/:id', function (req, res, next) { console.log('handling request'); res.sendStatus(200);
You will see this on the console:
before request handler handling request
Note that the last handler (the one that prints after request handler ) does not start. This is because you no longer say express to start the next handler.
That way, it doesn't really matter if your βmainβ handler (the one that returns 200) was successful or not, if you want the rest of the other participants to run, you should call next() .
For example, let's say you want to register all the requests coming to any database, regardless of whether the request succeeded. If you process this in the middleware after the main request handler, you must call next() in the main handler, or the log will not start.