Access "app" variable inside of ExpressJS/ConnectJS middleware?
Request objects have an app
field. Simply use req.app
to access the app
variable.
Generally I do the following.
var myMiddleware = require('./lib/mymiddleware.js')(app);...app.configure( function(){ app.use( myMiddleware ); ...}
And the middleware would look like this...
module.exports = function(app) { app.doStuff.blah() return function(req, res, next) { // actual middleware }}
You can also attach a variable to the Node global object, like so:
//some-module.jsglobal.someVariable = "some value!";//another-module.jsconsole.log(global.someVariable); // => "some value!"
Note that Nitzan Shaked's answer (using req.app) is a much better approach.
In fact, I don't advise using this solution at all. I'm leaving it solely for completeness, because it works, but it's bad practice in almost every situation (excepting adding polyfills).