NestJS Lifecycle Events
Nest notifies providers of lifecycle moments during startup and shutdown. This lesson covers the hooks you implement for connections, warmups, and cleanup.
Common Lifecycle Interfaces Implement interfaces like OnModuleInit, OnApplicationBootstrap, OnModuleDestroy, and BeforeApplicationShutdown on providers. Nest calls them at well-defined times while booting or closing the app.
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
async onModuleInit() { await this.$connect(); }
async onModuleDestroy() { await this.$disconnect(); }
} Database clients commonly connect on init and disconnect on destroy to avoid leaked connections.
Hook Order (Simplified) construct providers
-> onModuleInit
-> onApplicationBootstrap
(app running)
-> onModuleDestroy / beforeApplicationShutdown
-> onApplicationShutdown Use onModuleInit for per-module setup after DI is ready. Use onApplicationBootstrap when you need the whole app graph initialized. Enable shutdown hooks with app.enableShutdownHooks() for SIGTERM handling. Keep hooks idempotent and resilient—startup can be retried in containers. Lifecycle Hooks Cheatsheet Where to put startup/shutdown logic.
Hook Typical Use onModuleInit Connect DB, subscribe to streams onApplicationBootstrap Warm caches after all modules init onModuleDestroy Close connections for a module beforeApplicationShutdown Stop accepting work gracefully onApplicationShutdown Final cleanup / logging
Graceful Shutdown In Kubernetes, pods receive SIGTERM. Enabling Nest shutdown hooks lets you finish in-flight requests and close brokers cleanly before exit.
const app = await NestFactory.create(AppModule);
app.enableShutdownHooks(); Request-Scoped Providers Request-scoped providers have different lifecycles. Prefer singleton providers for long-lived connections.
Common Mistakes Opening connections in constructors instead of onModuleInit. Forgetting shutdown hooks and leaking broker consumers on deploy. Doing heavy synchronous work in hooks and delaying boot health checks. Assuming hooks run in tests without initializing the Nest app context. Key Takeaways Lifecycle interfaces hook providers into Nest boot/shutdown. Connect resources on init; release them on destroy. Enable shutdown hooks for graceful production deploys. Prefer singletons for long-lived connections.
Pro Tip
Pair readiness probes with onApplicationBootstrap warmups so orchestrators only route traffic after critical caches/clients are ready.
Testing NestJS Controllers Go to next item