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

qodeninja picture qodeninja · Sep 18, 2013 · Viewed 15.5k times · Source

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.

Answer

Nitzan Shaked picture Nitzan Shaked · Sep 18, 2013

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