qodeninja
qodeninja

Reputation: 11266

Access "app" variable inside of ExpressJS/ConnectJS middleware?

This may not me be the right approach, but I want to conditionally add an object/parameter to the app variable inside of an expressJS/connectjS middleware call.

Since this function is a callback, what's the standard/best way to access app from inside a middleware call?

  //app.js
  var myMiddleware = require('./lib/mymiddleware.js');
  ...
  app.configure( function(){
    app.use( myMiddleware.func() );
    ...
  }

  if( 'object' !== typeof app.myObject ){
    cry( 'about it' );
  } 


  //mymiddleware.js
  module.exports.func = function( ){
    return function( req, res, next ){
       //append app object
       //app.myObject = {}
       next();
    }
  };

Note, this is not something for locals or settings to later be rendered, but something that will be used in routes and sockets later down the execution chain.

Upvotes: 42

Views: 17129

Answers (3)

Nitzan Shaked
Nitzan Shaked

Reputation: 13598

Request objects have an app field. Simply use req.app to access the app variable.

Upvotes: 117

Andrew Faulkner
Andrew Faulkner

Reputation: 3930

You can also attach a variable to the Node global object, like so:

//some-module.js
global.someVariable = "some value!";

//another-module.js
console.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).

Upvotes: 4

Morgan ARR Allen
Morgan ARR Allen

Reputation: 10678

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
  }
}

Upvotes: 10

Related Questions