Skip to content

OnModuleInit

reference
1 min readUpdated

Kind: Interface

Source: packages/common/interfaces/hooks/on-init.interface.ts

Part of: Common

Interface defining method called once the host module has been initialized.

OnModuleInit is a lifecycle hook interface for providers, controllers, and modules that need to run initialization logic after their host module has been fully initialized. Implement the onModuleInit() method to perform setup work such as validating configuration, establishing connections, or preparing in-memory resources before the application begins handling requests.

Diagram

mermaid
graph LR
  A[Application bootstraps] --> B[Host module initializes]
  B --> C[Provider/Controller implements OnModuleInit]
  C --> D[onModuleInit() executes]
  D --> E[Initialization resources ready]

Usage

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

@Injectable()
export class CacheService implements OnModuleInit {
  private connected = false;

  async onModuleInit(): Promise<void> {
    await this.connect();
    this.connected = true;
  }

  private async connect(): Promise<void> {
    // Initialize a cache client or preload required data.
  }
}

AI Coding Instructions

  • Implement OnModuleInit on providers, controllers, or modules that require setup after their containing module has initialized.
  • Define an onModuleInit() method; it may return void or Promise<void> for asynchronous initialization.
  • Keep initialization logic focused and fail fast when required configuration or dependencies are unavailable.
  • Do not use this hook for request-specific work; use it only for one-time module lifecycle setup.
  • Ensure dependencies used during initialization are declared through NestJS dependency injection.

Used by

7 references from 7 files. Each is a place in this repository where the symbol is actually used — go read one rather than trusting an example.

Imported by (7)

  • KafkaControllerintegration/microservices/src/kafka/kafka.controller.ts:15
  • KafkaConcurrentControllerintegration/microservices/src/kafka-concurrent/kafka-concurrent.controller.ts:24
  • HeroControllersample/04-grpc/src/hero/hero.controller.ts:17
  • PrismaServicesample/22-graphql-prisma/src/prisma/prisma.service.ts:9
  • AppModulesample/34-using-esm-packages/src/app.module.ts:7
  • DatabaseConnectionintegration/repl/src/database/database.connection.ts:3
  • callModuleInitHookpackages/core/hooks/on-module-init.hook.ts:37

Was this page helpful?

Download as PDF
OnModuleInit — NestJS head-to-head