9

I want to be able to pass different requests through different Express middleware stacks.

I think I need two express apps, and some way to branch. e.g.:

var app = express();
var alt_app = express();

app.use(logger('dev'));
app.use(bodyParser.json());

app.use(function(req, res, next) {
  if (some_condition(req)) {
    divert_request_to_alt_app();
  } else {
    next();
  }
}

app.use(middleware_that_must_not_affect_alt_app());
alt_app.use(middleware_that_only_affects_alt_app());

Is such a strategy possible?

If so, what should divert_request_to_alt_app() be?

If not, what are other approaches?

fadedbee
  • 42,671
  • 44
  • 178
  • 308
  • When you say "one NodeJS *server*" do you really mean "one NodeJS *process*"? Assuming you mean process, here's an [example](http://nerdpress.org/2012/04/20/hosting-multiple-express-node-js-apps-on-port-80/) of how you can host multiple apps under a single process. – James Apr 22 '15 at 12:31
  • 1
    Use [routers](http://expressjs.com/4x/api.html#router). – Ben Fortune Apr 22 '15 at 12:33
  • Have you tried using the [node http proxy](https://github.com/nodejitsu/node-http-proxy)? – SivaDotRender Apr 22 '15 at 12:35
  • @James I mean one HTTP server in one NodeJS process. – fadedbee Apr 22 '15 at 12:35
  • Does your "alt" app have different routes to your main app? – Ben Fortune Apr 22 '15 at 12:39
  • @BenFortune No, routing to the alt_app depends on only the hostname, at the moment, but I may need it to depend on other parts of `req`. – fadedbee Apr 22 '15 at 12:42
  • @chrisdew have a look at the example I posted, it shows how you can route different requests to different express instances based on host name. – James Apr 22 '15 at 13:33
  • @James the vhost example looks like it is not for express 4.x - the post is dated 2012. There are confusingly two vhost modules on npm. – fadedbee Apr 22 '15 at 14:18

1 Answers1

8

I found that express apps are functions. Calling them with (req, res, next) is all you need to do to pass a request from one app to another.

In the example below, I have one root app app and two branches app0 and app1.

var app0 = require('./app0');
var app1 = require('./app1');

var app = express();
...
app.use(function(req, res, next) {
  if (some_condition_on(req)) {
    app0(req, res, next);
  } else {
    app1(req, res, next);
  }
});
fadedbee
  • 42,671
  • 44
  • 178
  • 308