Discover how to make your app start and stop smoothly without headaches!
Why Application lifecycle in NestJS? - Purpose & Use Cases
Imagine building a server that needs to start, run tasks, and then clean up resources when it stops. You try to manage all these steps manually by writing separate code everywhere.
Manually handling start, stop, and cleanup is confusing and easy to forget. It leads to bugs like memory leaks or services not shutting down properly, making your app unstable.
Application lifecycle hooks in NestJS let you run code automatically at key moments like startup and shutdown. This keeps your app organized and reliable without extra hassle.
async function start() { connectDb(); startServer(); }
async function stop() { closeDb(); stopServer(); }class AppService implements OnModuleInit, OnModuleDestroy {
onModuleInit() { connectDb(); }
onModuleDestroy() { closeDb(); }
}You can build apps that manage resources cleanly and respond to lifecycle events without messy code scattered everywhere.
A NestJS app connects to a database when it starts and closes the connection safely when it stops, preventing data loss or crashes.
Manual lifecycle management is error-prone and scattered.
Lifecycle hooks centralize startup and shutdown logic.
This leads to cleaner, safer, and more maintainable apps.
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
