DEV Community

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

Posted 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, OnApplicationBootstrap } from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';

@Module({})
export class AppModule implements OnApplicationBootstrap {
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}

  // or using the 'onModuleInit' lifecycle hook
  onApplicationBootstrap(): Promise<void> {
    this.httpAdapterHost.listen$.subscribe(() =>
      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.

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

Top comments (0)