Is there a way to inject middleware in an Express stack? What I mean is I want to have my app.js setup the main middleware chain, and then call other modules passing the app instance and they may want to insert more middleware (e.g. an authentication module that wants to add passport in at the correct place)
3 Answers
You can certainly pass your app
object to other modules and call use
there. Of course, middleware functions are executed in the order they are added, so you have to take great care to ensure that you call use
in the correct order.
app.js
var app = express();
// ...
app.use(express.logger()); // first middleware function
var someOtherModule = require('./mod.js');
someOtherModule.init(app);
app.use(express.static()); // last middleware function)
mod.js
exports.init = function(app) {
app.use(function(req, res, next) {
});
};
As far as actually injecting a middleware function in the middle of the stack (after you've already called app.use
with a set of middleware functions), there's no documented way to do it. use
only adds a function to the end of the stack.
use
is actually supplied by Connect in proto.js:
app.use = function(route, fn){
...
this.stack.push({ route: route, handle: fn });
return this;
};
Technically, you could fiddle with app.stack
yourself, but I would not do this. You'd be messing with an undocumented implementation detail, which is liable to change. In other words, it's possible a future update to either Connect or Express could break your app.
-
Thanks - I didn't think there was a way (can't think of an easy way to say where it would be put). I'm probably going to go with the way you suggest up front. Dec 4, 2012 at 10:22
-
1
You can use app.use(fn) or stack them like this:
app.get('/foo', fn1, fn2, fn3);
The signature has to always be the same and call next();
function(req, res, next) {
next();
}
I don't understand what is the problem?
You can add any function in middleware:
app.use(function(req,res,next){
//some munipulation with req and res
next()
})
And you can send this app
into you're moduls
-
3I think the problem is that
app.use
always adds your middleware function to the end of the stack, so middleware added earlier may complete the request before you function gets a chance to run.– josh3736Dec 3, 2012 at 20:51 -
-
To try and keep things more modular - so I want everything to do with authentication in authenticate.js - it creates the passport object inside there so rather than pass it out I'd rather pass app in and ket that module add the passport.initialize and passport.session middleware just after the express.session but before router Dec 3, 2012 at 21:26
-
But you can create a module authentification and make somethings like module.exports = exports = function(app){ ///here add all with passport } Dec 3, 2012 at 21:37