How to reference the app instance in a module in Nest.js

I'm working on a project that's using multiple Nest repos, around 4. Every repo needs to implementing logging to log things like

  • Server lifecycle events
  • Uncaught errors
  • HTTP requests/responses

Ideally, I'd like to package everything up into a module which I can publish to my company's NPM organization and just consume directly in each of my projects. That way, it would take very minimal code to get logging set up in each project.

One of the things I'd like to log in my server lifecycle event is the server's url. I know you can get this via app.getUrl() in the bootstrapping phase, but it would be great to have access to the app instance in a module's lifecycle hook like so.

@Module({})
export class LoggingModule implements NestModule {
  onApplicationBootstrap() {
    console.log(`Server started on ${app.getUrl()}`)
  }
  beforeApplicationShutdown() {
    console.log('shutting down')
  }
  onApplicationShutdown() {
    console.log('successfully shut down')
  }
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggingMiddleware).forRoutes('*')
  }
}

Is this possible?


Solution 1:

There's no way (besides hacky ones, maybe) to access the app itself inside modules.

As you can see here, app.getUrl() uses the underlying HTTP server. Thus I guess you can retrieve the same data using the provider HttpAdapterHost.