Kishore Indraganti
Kishore Indraganti

Reputation: 1322

Place of middleware in express js really matters?

I am trying to use a middleware for my application so as a POC I just made a simple middleware for my application with the following code.

var processingPage = function(req, res, next) {
    console.log("Req.Query "+req.url);
    next();
}

// all environments
app.set('port', process.env.PORT || 4000);
app.use(express.compress());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(allowCrossDomain);
app.use(processingPage);

At this stage the processingPage midlleware dint work when request comes,So I changed the code like below(Moved app.use(processingPage); to top)

var processingPage = function(req, res, next) {     
    console.log("Req.Query "+req.url);
    next();
}

// all environments
app.set('port', process.env.PORT || 4000);
app.use(express.compress());
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(processingPage);
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
app.use(allowCrossDomain);

after this the middleware starts to work . Why this behaviour?

Upvotes: 0

Views: 31

Answers (1)

robertklep
robertklep

Reputation: 203231

Because middleware is processed in order in which it is declared (Express doesn't have a way to declare middleware dependencies or priorities, so it needs to infer the order in which the middleware is executed by when it is app.use()'d).

By moving your middleware to the end of the chain, the chance that another middleware sends back a response (and ending the middleware chain) is quite large.

My guess is that the request you're testing with is being handled by app.router or express.static.

This also means that allowCrossDomain should be moved upwards in the middleware chain, due to the same reason.

Upvotes: 1

Related Questions