2

TL/DR: Is there a way to combine two apps with express, and fall back to the second app if the first doesn't implement a route?

We currently have two express apps, a new well-factored app and an old, deprecated app. Going forward, our team will be slowly migrating everything in the old app to the new app.

I'm looking for a way to combine the two apps so they can both be called. I realized I can do something like this using app.use, but that requires the apps to be on separate subdomains or use separate base paths. My goal is to keep the routes the same, so a person calling the API is unaware of the changes happening under the hood.

For example, it would be great if I could do something like this:

const express = require('express');
let oldApp = express();
let newApp = express();

oldApp.get('/old', function (req, res) {
  res.send("OLD");
});

newApp.get('/new', function (req, res) {
  res.send("NEW");
});

express().use(oldApp, newAPp).listen(3000);

Then, I could call localhost:3000/old or localhost:3000/new and both endpoints would work.

Community
  • 1
  • 1
LandonSchropp
  • 10,084
  • 22
  • 86
  • 149
  • 2
    The path is optional for `.use`, so you could do `.use(oldApp).use(newApp)` – Explosion Pills Dec 13 '16 at 19:20
  • Exactly. It might need some work though, e.g. you must remove the 404 handling in `oldApp`. Also I'm not sure whether you can directly `use()` and `express()` instance. You might have to switch to `express.Router()`, in this case you could have problems with some settings (e.g. template engine, etc.). – svens Dec 13 '16 at 19:32
  • @ExplosionPills This worked great! Would you mind adding your comment as an answer so I can accept it? Thanks for the help! – LandonSchropp Dec 13 '16 at 21:31

1 Answers1

1

The path is optional for .use. You can apply the middleware and any routes that are handled by that middleware will be used first.

express.use(oldApp).use(newApp)

If you did .use(oldApp, newApp) it would try to interpret oldApp as a path.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405