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)
Share
You can certainly pass your
appobject to other modules and callusethere. Of course, middleware functions are executed in the order they are added, so you have to take great care to ensure that you callusein the correct order.app.js
mod.js
As far as actually injecting a middleware function in the middle of the stack (after you’ve already called
app.usewith a set of middleware functions), there’s no documented way to do it.useonly adds a function to the end of the stack.useis actually supplied by Connect in proto.js:Technically, you could fiddle with
app.stackyourself, 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.