title: How to use nested middleware in express.js
body: <p>I want to make a change from the actual structure of my code. This is the actual code i have:</p>
  
  <pre class="lang-js prettyprint-override"><code>//index.js
  var routes = require('./routes');
  var subdomain = require('express-subdomain');
  
  //require express app with settings
  var app = require('./app');
  
  //export the application
  module.exports = app;
  
  // routes request like endusers-api.mydomain.ext/
  app.use(subdomain('endusers-api', routes.apis.endusers));
  // routes request like mydomain.ext/
  app.use(routes.webapps.endusers);
  
  
  //routes/index.js
  var apis = {endusers: require("./apis/endusers")}
  var webapps = {endusers: require("./webapps/endusers")}
  var routes = {apis: apis,   webapps: webapps}
  
  module.exports = routes;
  
  
  //routes/apis/endusers
  var express = require('express');
  var route = express.Router();
  var logger = require('../../lib/logger');
  
  route.get('/', logger("endusers-api-access"), function(req, res, next) {
      res.json({
          "name" : "Endusers API"
      });
  });
  
  module.exports = route;
  
  
  //routes/webapps/endusers.js
  var express = require('express');
  var route = express.Router();
  var logger = require('../../lib/logger');
  
  route.get('/', logger("endusers-webapp-access"), function(req, res, next) {
      res.render('endusers/index', {title: 'Homepage'});
  });
  
  module.exports = route;
  </code></pre>
  
  <p>Now I want to change the above code to this (feel free to tell me if this is a good approach of doing things in Node.js or not):</p>
  
  <pre class="lang-js prettyprint-override"><code>//index.js
  var middlewares = require('./middlewares');
  var app = require('./app');
  
  module.exports = app;
  
  //i want to change to this
  app.use(middlewares.endusersApi);
  app.use(middlewares.endusersWebapp);
  
  //Stuff for creating server and listening...
  
  
  //middlewares/index.js
  var middlewares = {
    endusersApi : require("./apis/endusers"), 
    endusersWebapp : require("./webapps/endusers")
  }
  
  module.exports = middlewares;
  
  
  //middlewares/apis/endusers.js
  //TODO
  
  
  //middlewares/webapps/endusers
  //TODO
  </code></pre>
  
  <p>How should I write the <code>TODO</code> portions above. It look like we will need nested middlewares (a middleware calling another middleware). Please, your suggestions.</p>