The application lifecycle in NestJS helps you control what happens when your app starts, runs, and stops. It makes sure your app sets up and cleans up properly.
0
0
Application lifecycle in NestJS
Introduction
When you want to run some code right after the app starts, like connecting to a database.
When you need to clean up resources before the app stops, like closing database connections.
When you want to perform tasks during app shutdown, such as saving logs or clearing caches.
When you want to listen to lifecycle events to manage app behavior smoothly.
Syntax
NestJS
import { Injectable, OnModuleInit, OnModuleDestroy, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; @Injectable() export class MyService implements OnModuleInit, OnModuleDestroy, OnApplicationBootstrap, OnApplicationShutdown { onModuleInit() { // Called once the module has been initialized } onApplicationBootstrap() { // Called once the entire application has bootstrapped } onModuleDestroy() { // Called before the module is destroyed } onApplicationShutdown(signal?: string) { // Called before the application shuts down } }
Use lifecycle hooks by implementing the interfaces in your service or provider.
Each hook runs at a specific time during app start or stop.
Examples
This runs code right after the module is ready.
NestJS
export class AppService implements OnModuleInit { onModuleInit() { console.log('Module initialized'); } }
This runs code when the app is about to stop, showing the shutdown signal.
NestJS
export class AppService implements OnApplicationShutdown { onApplicationShutdown(signal?: string) { console.log(`App shutting down due to: ${signal}`); } }
Sample Program
This example shows a service that logs messages when the app module starts and when the app shuts down. It helps you see the lifecycle in action.
NestJS
import { Injectable, OnModuleInit, OnApplicationShutdown } from '@nestjs/common'; @Injectable() export class LifecycleService implements OnModuleInit, OnApplicationShutdown { onModuleInit() { console.log('App module has been initialized'); } onApplicationShutdown(signal?: string) { console.log(`App is shutting down. Signal: ${signal ?? 'none'}`); } } // In main.ts import { NestFactory } from '@nestjs/core'; import { Module } from '@nestjs/common'; @Module({ providers: [LifecycleService], }) class AppModule {} async function bootstrap() { const app = await NestFactory.create(AppModule); await app.listen(3000); } bootstrap();
OutputSuccess
Important Notes
Lifecycle hooks help manage resources like database connections cleanly.
Use the shutdown signal to know why the app is stopping (like Ctrl+C or system shutdown).
Not all hooks are required; implement only what you need.
Summary
Application lifecycle hooks let you run code at key app moments.
Use OnModuleInit to run code after module setup.
Use OnApplicationShutdown to clean up before the app stops.