DEV Community

Micael Levi L. C.
Micael Levi L. C.

Posted on • Edited on

NestJS tip: how to run operations when the HTTP server is ready

Let's say you want to perform few tasks right after your HTTP server is ready to handle connections. Starting from @nestjs/core v10.4.8, you can now do this in a idiomatic way like the following:

// app.module.ts
import { Module } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';

@Module({})
export class AppModule {
  constructor(readonly httpAdapterHost: HttpAdapterHost) {
    httpAdapterHost.listen$.subscribe({
      complete: () => this.onHttpServerListening(),
    });
  }

  async onHttpServerListening(): Promise<void> {
    console.info('HTTP server is listening');
  }
}
Enter fullscreen mode Exit fullscreen mode

That console.info statement will be called after app.listen() succeeds. If the onHttpServerListening throw any error, the application will crash due to that!

You can read more about this feature here: https://docs.nestjs.com/faq/http-adapter#listening-event

Top comments (1)

Collapse
 
orphe_h00 profile image
Bobby Orphé HOUESSINON

Thanks for the tip.