Understanding Life Cycle Hooks in NestJS

@rnab
3 min readJan 27, 2025

--

NestJS is a powerful, progressive Node.js framework that offers rich support for building efficient, scalable, and enterprise-grade server-side applications. One of the many features that make NestJS unique is its life cycle hooks. Understanding these hooks can significantly enhance how developers manage the initialization and disposal of resources in their applications. In this article, we will explore these life cycle hooks and how to use them effectively in your NestJS applications.

What Are Life Cycle Hooks?

In NestJS, life cycle hooks are callbacks that allow developers to tap into key events that occur during the lifetime of an application or its components. These hooks enable you to execute custom logic at specific times during the life cycle, such as during the application’s initialization, request processing, or shutdown events.

Key Life Cycle Hooks in NestJS

NestJS provides several life cycle hooks that you can implement within your applications. Here are the primary hooks you should be familiar with:

  1. onModuleInit: This hook is executed once a module has been initialized. It’s useful for any setup or initialization logic that needs to run after the module’s providers have been created.
  2. onModuleDestroy: This hook is executed when an application needs to clean up resources associated with a module before it is destroyed.
  3. onApplicationBootstrap: This hook is called after the entire application has bootstrapped successfully. It is typically used for any initialization logic that should happen after all modules have been initialized.
  4. beforeApplicationShutdown: This hook is invoked just before the application is shut down, allowing you to perform any necessary cleanup operations.
  5. afterApplicationShutdown: This hook is executed after the application has completely shut down.

Implementing Life Cycle Hooks

Let’s go through the implementation of these life cycle hooks in a NestJS service using TypeScript.

Example: Using onModuleInit and onModuleDestroy

Below is an example service demonstrating the use of onModuleInit and onModuleDestroy hooks.

import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';

@Injectable()
export class TaskService implements OnModuleInit, OnModuleDestroy {
private tasks: string[] = [];

onModuleInit() {
console.log('Module initialized');
// Initialize default tasks
this.tasks.push('Initial Task');
}

onModuleDestroy() {
console.log('Module destroyed');
// Cleanup tasks
this.tasks = [];
}

getTasks(): string[] {
return this.tasks;
}
}

Example: Using onApplicationBootstrap

Here’s an example demonstrating the use of onApplicationBootstrap.

import { Injectable, OnApplicationBootstrap } from '@nestjs/common';

@Injectable()
export class AppService implements OnApplicationBootstrap {
onApplicationBootstrap() {
console.log('Application has been bootstrapped');
}

performCriticalTask() {
console.log('Performing a critical task');
}
}

Example: Using beforeApplicationShutdown

Implementing graceful shutdown logic using beforeApplicationShutdown.

import { Injectable, BeforeApplicationShutdown } from '@nestjs/common';

@Injectable()
export class DatabaseService implements BeforeApplicationShutdown {
beforeApplicationShutdown(signal: string) {
console.log(`Preparing to shut down, received signal: ${signal}`);
// Perform database disconnection logic
return new Promise((resolve) => {
console.log('Closing database connections...');
setTimeout(() => {
console.log('Database connections closed');
resolve();
}, 3000);
});
}
}

When to Use Life Cycle Hooks?

Life cycle hooks in NestJS come in handy in various scenarios, such as:

  • Resource Management: Allocating resources (e.g., database connections) during initialization and cleaning up during shutdown.
  • Service Initialization: Running setup code once all modules and their dependencies are set up.
  • Logging and Monitoring: Monitoring application’s bootstrapping process or shutdown sequence.
  • Interdependent Module Initialization: Ensuring that modules are initialized in a specific order.

Conclusion

Life cycle hooks in NestJS provide developers with a powerful tool to manage the application’s initialization and shutdown sequences effectively. By integrating these hooks correctly, you can significantly improve how your application manages resources and responds to various runtime events.

The well-thought-out architectural design of NestJS, combined with features such as life cycle hooks, makes it an excellent choice for building robust, scalable applications. As you implement these hooks in your applications, you will find the balance between modularity and tightly-controlled resource handling a significant asset in the lifecycle management of your server-side applications.

--

--

@rnab
@rnab

Written by @rnab

Typescript, Devops, Kubernetes, AWS, AI/ML, Algo Trading

No responses yet