3

Is there a proper way to migrate an app based on express.js to a nest.js app, doing so route by route ? I couldn't find official documentation or open question about this.

Only support i could find was this opened question: Migrating Express application to NestJS

Sufiane
  • 1,507
  • 1
  • 14
  • 23
  • Hey did you find anything on this? – Android Geek Dec 07 '22 at 06:39
  • Well from what I know its not possible. Since nest start a server on its own. You would need 2 servers, the legacy and the new one and then migrate endpoint by endpoint as you please – Sufiane Jan 03 '23 at 13:42

1 Answers1

1

It's been long time since you asked but FWIW here we go for anyone who inherited legacy Express app like I just did.

You can use your legacy Express application as part of NestJS using ExpressAdapter. You just create (or import) the express() app with all it's routes and then start Nest. The routes from legacy should be there so over time you just add routes to the Nest controllers/services modules and delete them from the legacy app.

import express, {json, urlencoded} from "express";
// imports legacy API; the file exports `module.exports = router;`
// where router is `const router = express.Router();`
import api from './legacy/routes/api.cjs';

config();

const expressApp = express();
expressApp.use(json());
expressApp.use(urlencoded({extended: false}));
expressApp.use('/api', api);

async function bootstrap() {
  const adapter = new ExpressAdapter(expressApp);
  const app = await NestFactory.create(AppModule, adapter);
  await app.listen(3000);
}
bootstrap();

You should NOT start the server in the legacy app as Nest will do that for you. Comment out something like this that might be there in legacy:

const server = http.createServer(app);
server.listen(port, () => logger.logger.info(`API running on localhost:${port}`));

It seems to work for me so far.

PeS
  • 3,757
  • 3
  • 40
  • 51
  • its been indeed a long time ! i wish i had this before haha ! – Sufiane Jun 22 '23 at 15:33
  • 1
    @Sufiane yup, it is kind of interesting there are not many examples or docs available. I envy you that you have probably already finished this, I have a long journey ahead :( – PeS Jun 23 '23 at 08:37
  • keep the faith ! its gonna be quicker than you think ! – Sufiane Jun 26 '23 at 07:59