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.
Application lifecycle in 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.
export class AppService implements OnModuleInit { onModuleInit() { console.log('Module initialized'); } }
export class AppService implements OnApplicationShutdown { onApplicationShutdown(signal?: string) { console.log(`App shutting down due to: ${signal}`); } }
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.
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();
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.
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.
Practice
Solution
Step 1: Understand module initialization timing
The OnModuleInit hook runs immediately after the module's dependencies are resolved and the module is set up.Step 2: Match the hook to the description
OnApplicationBootstrap runs after the entire app starts, OnApplicationShutdown runs before app stops, and OnModuleDestroy runs before module is destroyed.Final Answer:
OnModuleInit -> Option AQuick Check:
Run code after module setup = OnModuleInit [OK]
- Confusing OnModuleInit with OnApplicationBootstrap
- Using OnApplicationShutdown for startup code
- Thinking OnModuleDestroy runs after module init
Solution
Step 1: Identify correct interface and method signature
The OnApplicationShutdown interface requires implementing onApplicationShutdown(signal?: string) method.Step 2: Check method name and parameter types
export class MyService implements OnApplicationShutdown { onApplicationShutdown(signal?: string) { /* code */ } } correctly implements OnApplicationShutdown with optional string parameter signal. Others mismatch interface or method name.Final Answer:
export class MyService implements OnApplicationShutdown { onApplicationShutdown(signal?: string) { /* code */ } } -> Option AQuick Check:
Correct interface and method signature = export class MyService implements OnApplicationShutdown { onApplicationShutdown(signal?: string) { /* code */ } } [OK]
- Implementing wrong interface for shutdown hook
- Using wrong method name or parameters
- Confusing OnApplicationShutdown with OnModuleInit
export class AppService implements OnModuleInit, OnApplicationShutdown {
onModuleInit() {
console.log('Module initialized');
}
onApplicationShutdown(signal?: string) {
console.log('App shutting down:', signal);
}
}What will be printed if the application starts and then receives a SIGINT signal to stop?
Solution
Step 1: Understand lifecycle hook order on start
onModuleInit runs after module setup, so 'Module initialized' prints on app start.Step 2: Understand shutdown hook on SIGINT
When SIGINT signal is received, onApplicationShutdown runs and logs 'App shutting down: SIGINT'.Final Answer:
Module initialized\nApp shutting down: SIGINT -> Option DQuick Check:
Start logs init, stop logs shutdown with signal [OK]
- Assuming shutdown logs before startup
- Missing signal parameter in shutdown log
- Thinking only one hook runs
export class MyService implements OnApplicationShutdown {
onApplicationShutdown() {
console.log('Cleaning up');
}
}What is the error and how to fix it?
Solution
Step 1: Check method signature for OnApplicationShutdown
The interface requires onApplicationShutdown(signal?: string) with an optional string parameter.Step 2: Identify missing parameter in method
The method lacks the optional signal parameter, causing a signature mismatch error.Final Answer:
Missing optional signal parameter in onApplicationShutdown method -> Option CQuick Check:
Method signature must match interface including optional parameters [OK]
- Omitting optional signal parameter
- Using wrong method name
- Confusing OnApplicationShutdown with OnModuleDestroy
Solution
Step 1: Choose correct lifecycle hook for app shutdown
OnApplicationShutdown runs when the app is stopping and receives the shutdown signal.Step 2: Filter signal inside onApplicationShutdown method
Inside onApplicationShutdown(signal?: string), check if signal === 'SIGTERM' to run cleanup only for that signal.Final Answer:
Implement OnApplicationShutdown and check if signal === 'SIGTERM' inside onApplicationShutdown method -> Option BQuick Check:
Filter shutdown signal inside OnApplicationShutdown hook [OK]
- Using OnModuleDestroy which runs on module destroy, not app shutdown
- Trying to detect shutdown in OnApplicationBootstrap
- Manually overriding bootstrap instead of lifecycle hooks
Ready to prove it?
Pass the test and this pattern moves unknown
