🧩 Built-in Plugins

Plugin Lifecycle Hooks

Understand the plugin initialization and teardown lifecycle.

Lifecycle Phases

Diagram; its source is available below
Diagram source
graph LR
    Module[Module Create] --> Init[onModuleInit]
    Init --> App[App Bootstrap]
    App --> Ready[onApplicationBootstrap]
    Ready --> Running[Running...]
    Running --> Shutdown[onModuleDestroy]
    Shutdown --> Done[beforeApplicationShutdown]

NestJS Lifecycle Hooks

HookWhen Called
onModuleInit()After module instantiation
onApplicationBootstrap()After all modules initialized
onModuleDestroy()Before module teardown
beforeApplicationShutdown()Before app stops

Implementation

import {
  Module,
  OnModuleInit,
  OnApplicationBootstrap,
  OnModuleDestroy,
} from "@nestjs/common";

@Module({
  /* ... */
})
export class MyPluginModule
  implements OnModuleInit, OnApplicationBootstrap, OnModuleDestroy
{
  async onModuleInit() {
    console.log("Plugin module initialized");
    // Register entities, set up connections
  }

  async onApplicationBootstrap() {
    console.log("Application fully started");
    // Start background tasks, subscribe to events
  }

  async onModuleDestroy() {
    console.log("Plugin shutting down");
    // Cleanup connections, stop timers
  }
}

Common Init Tasks

PhaseTasks
onModuleInitRegister entities, validate config
onApplicationBootstrapStart schedulers, connect to external services
onModuleDestroyClose connections, flush queues

Edit this page

Copyright © 2023-Present Ever Co. LTD.Docs by Sourcey