Lifecycle hooks

Interfaces invoked at key phases of module and application bootstrap and shutdown.

Since NestJS 10/11 Spec ↗

Syntax

onModuleInit | onApplicationBootstrap | onModuleDestroy | beforeApplicationShutdown | onApplicationShutdown

Returns

void | Promise<void> — Hook methods may be async; Nest awaits them.

Examples

import {
  Injectable, OnModuleInit, OnModuleDestroy,
} from '@nestjs/common';

@Injectable()
export class DbService implements OnModuleInit, OnModuleDestroy {
  async onModuleInit() {
    await this.connect();
  }
  async onModuleDestroy() {
    await this.disconnect();
  }
}

Notes

Order is onModuleInit, then onApplicationBootstrap on startup; the reverse on shutdown. Call app.enableShutdownHooks() so onModuleDestroy and onApplicationShutdown run on SIGTERM/SIGINT.