Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two Express "app"s in one NodeJS server?

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?

like image 811
fadedbee Avatar asked Apr 22 '15 12:04

fadedbee


1 Answers

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);
  }
});
like image 114
fadedbee Avatar answered Sep 28 '22 07:09

fadedbee