SenG
SenG

Reputation: 731

Adding NestJS as express module results in Nest being restarted

We are progressively migrating our app from the NestJS framework to Express and thought of including NestJS as a module of Express so the migration can be done in small batches. Things seem to be connected but the NestJS seems to be a restart for every request. This is not a bug but a general approach on how to coexist Express & NestJS would be appreciated.

Express + NestJS repo https://gitlab.com/vijaysvj/express-with-nest/-/tree/master/

References:

  1. Import a Nest.js app as a simple Express middleware

  2. Migrating Express application to NestJS

  3. Use NestJs package in nodejs/express project

  4. https://expressjs.com/en/api.html#app.mountpath

  5. https://github.com/tzkmx/nestjs-graphql-as-express-subapp

  6. https://newbedev.com/import-a-nest-js-app-as-a-simple-express-middleware

Upvotes: 2

Views: 1532

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70121

What would almost be an undoubtedly better approach would be to pass the current express application to an ExpressAdapter for Nest, and then run the NestJS server, instead of trying to cram the NestJS server into the Express server. Something like this:

const bootstrap = async () => {
  const adapter = new ExpressAdapter(expressApp); // from @nestjs/platform-express
  const app = await NestFactory.create(AppModule, adapter);
  await app.listen(3000);
}

bootstrap();

Where expressApp is your already created express application. Doing this will allow all of your express functionality to still exist while you migrate over to NestJS. Just make sure to migrate any error handlers and post-request middleware to the appropriate Nest enhancers (like Filters and Interceptors).

Upvotes: 2

Related Questions