According to the express documentation at http://expressjs.com/guide/using-middleware.html
If the current middleware does not end the request-response cycle, it must call next() to pass control to the next middleware, otherwise the request will be left hanging.
therefore, if the middleware needs to complete the request-request earlier, just do not call next() , but make sure the middleware does complete the request-response by calling res.end , res.send , res.render or any method that implicitly calls res.end
app.use(function (req, res, next) { if () { res.end(); } else { next(); } });
Here is a server example showing that it is running
var express = require('express'); var app = express(); var count = 0; app.use(function(req, res, next) { console.log('f1'); next(); }) app.use(function(req, res, next) { console.log('f2'); if (count > 1) { res.send('Bye'); } else { next(); } }) app.use(function(req, res, next) { console.log('f3'); count++; next(); }) app.get('/', function (req, res) { res.send('Hello World: ' + count); }); var server = app.listen(3000);
you will see after 3 requests, the server shows "Bye" and f3 is not reached
Jerome WAGNER
source share