visionmedia/express — Issue #943: Sequential coupling in route/middleware initialization
Author: ovaillancourt
Created: 2011-12-28 16:30:37+00:00
State: open

When putting the route definitions _before_ the middleware stack definition, it seems like the routes are bound to the middleware stack in the state that it was at the moment the first route was created, which makes some hard to track sequential coupling for complex initialization processes.

Given the lightweight/kiss nature of express, I understand that this *might* be done by design. However, I'd advise documenting the exact behavior clearly. (ie: That the middleware stack bound to a route corresponds to the state of the middleware stack at the moment where the first route was created.)

To reproduce:

```javascript
var express = require('express');
var should = require('should');

// Create express app;
var app = express.createServer();

// Route here, which fails
app.get('/', function(req,res){
// We *should* receive the value here given the custom middleware
// was supposed to have put it.
should.exist(req._magic);
return res.send('Hello World!');
});

// Middleware stack
//Small mw setting a custom var in the req for the tests.
app.use(function(req,res,next){req._magic = '42';next();});
app.use(app.router); //Router right there

// Another route, defined after the mw stack. it will also fail.
app.get('/test', function(req,res){
should.exist(req._magic);
return res.send('Hello World!');
});

// Start server
app.listen(3000);

```

Move the middleware stack above all the routes definition to get it all working.