Plugin Lifecycle Hooks
Understand the plugin initialization and teardown lifecycle.
Lifecycle Phasesβ
NestJS Lifecycle Hooksβ
| Hook | When 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β
| Phase | Tasks |
|---|---|
onModuleInit | Register entities, validate config |
onApplicationBootstrap | Start schedulers, connect to external services |
onModuleDestroy | Close connections, flush queues |
Related Pagesβ
- Plugin Dev Quickstart β getting started
- Plugin Entity Registration β entities
- Plugin Configuration β config