In NestJS, which lifecycle hook methods can a provider implement, and in what order does Nest call them from boot to shutdown?
answer
- two at boot, three at shutdown
- module init before app bootstrap
- app.close() or an opted-in signal
- server closes before the last one
basics
~10 sNestJS calls onModuleInit, then onApplicationBootstrap when the app initializes, and onModuleDestroy, beforeApplicationShutdown and onApplicationShutdown, in that order, when app.close() runs or an opted-in shutdown signal arrives.
solid answer
~30 sNest has five hooks, each with an interface in `@nestjs/common`. `onModuleInit()` runs once the host module's dependencies are resolved, and `onApplicationBootstrap()` once every module is initialized but before the app listens; both fire on `app.init()` or `app.listen()`. At shutdown Nest calls `onModuleDestroy()`, then `beforeApplicationShutdown(signal)`, then closes the HTTP server, then calls `onApplicationShutdown(signal)`. The shutdown hooks run on an explicit `app.close()`, or on a signal such as `SIGTERM` only after you called `app.enableShutdownHooks()`. An async hook is awaited before the sequence moves on, and request-scoped classes get no hooks at all.
code
typescript · 34 linesimport {
BeforeApplicationShutdown,
Injectable,
OnApplicationBootstrap,
OnApplicationShutdown,
OnModuleDestroy,
OnModuleInit,
} from '@nestjs/common';
@Injectable()
export class LifecycleLogger
implements
OnModuleInit,
OnApplicationBootstrap,
OnModuleDestroy,
BeforeApplicationShutdown,
OnApplicationShutdown
{
onModuleInit() {
console.log('1 onModuleInit');
}
onApplicationBootstrap() {
console.log('2 onApplicationBootstrap');
}
onModuleDestroy() {
console.log('3 onModuleDestroy');
}
beforeApplicationShutdown(signal?: string) {
console.log('4 beforeApplicationShutdown', signal);
}
onApplicationShutdown(signal?: string) {
console.log('5 onApplicationShutdown', signal);
}
}go deeper
Recall the five method names and their order: two boot hooks, then the three shutdown hooks with the server closing before the last one.
Explain what triggers each phase: init() or listen() for boot, close() or an opted-in signal for shutdown, and that async hooks are awaited.
Show you know which instances get no hooks, request-scoped ones in particular, and that close() does not end the process.
Treat the hooks as the app's contract for owned resources: every connection opened at boot should have a matching close in a shutdown hook, and teams should review that pairing.
## What a lifecycle hook is in NestJS NestJS owns the life of every **module**, **provider** and **controller** it creates: it constructs them, wires their dependencies and, at the end, tears the application down. A **lifecycle hook** is a method with a reserved name that Nest calls on those instances at a fixed point in that life. You register one simply by giving the class that method. Each hook has a matching interface in `@nestjs/common`: `OnModuleInit`, `OnApplicationBootstrap`, `OnModuleDestroy`, `BeforeApplicationShutdown` and `OnApplicationShutdown`. The interfaces are optional, because TypeScript interfaces disappear at compile time and Nest only checks whether the method exists, but implementing them gets the signature type-checked and documents intent. ## The five hooks in order The documentation splits an application's life into three phases, **initializing**, **running** and **terminating**, and the hooks sit at the edges of the running phase: | Hook | Phase | When Nest calls it | |---|---|---| | `onModuleInit()` | boot | once the host module's dependencies are resolved | | `onApplicationBootstrap()` | boot | once all modules are initialized, before the app listens | | `onModuleDestroy()` | shutdown | first, when the shutdown sequence starts | | `beforeApplicationShutdown(signal)` | shutdown | after every `onModuleDestroy()` has settled | | `onApplicationShutdown(signal)` | shutdown | after connections close, as the last step of `app.close()` | As a sequence, one run of a Nest HTTP application looks like this: 1. Nest scans the module graph and instantiates the providers and controllers. 2. It calls `onModuleInit()` across all modules, then `onApplicationBootstrap()` across all modules. 3. The HTTP server starts listening and the app serves traffic. 4. On shutdown it calls `onModuleDestroy()`, then `beforeApplicationShutdown()`. 5. It closes the HTTP server and the other listeners it owns. 6. It calls `onApplicationShutdown()`. `beforeApplicationShutdown()` and `onApplicationShutdown()` receive the signal name as their first argument (for example `'SIGTERM'`); `onModuleDestroy()` takes no arguments. On a plain `app.close()` with no argument, the signal is `undefined`. ## What triggers each phase - The boot hooks fire when the application is **initialized**: an explicit `app.init()`, `app.listen()` (which initializes first if that has not happened), or `NestFactory.createApplicationContext()`, which initializes the standalone context for you. - `NestFactory.create()` on its own does **not** run them: it builds the application object and stops there. - The shutdown hooks fire on an explicit `app.close()`. - They also fire when the process receives a signal such as `SIGTERM`, but **only** if `app.enableShutdownHooks()` was called at bootstrap. Signal listeners are off by default because they cost resources. - `app.close()` runs the shutdown sequence and closes the server; it does not end the Node process, so an open interval or background task keeps it alive. ## Async hooks are awaited Any hook may return a `Promise` or be declared `async`. Nest awaits it before the sequence continues, so an `onModuleInit()` that loads data delays the rest of boot, and an `onModuleDestroy()` that drains work delays the next shutdown step. That is the point of the hooks: a guaranteed place to finish work before the next phase begins. ```typescript import { Injectable, OnModuleInit } from '@nestjs/common'; @Injectable() export class RatesService implements OnModuleInit { private rates = new Map<string, number>(); async onModuleInit(): Promise<void> { // Nest awaits this before it continues booting this.rates.set('EUR', 1); } } ``` ## Which instances get hooks - **Providers, controllers and module classes** all receive hooks; a module class's own hook runs after the hooks of its providers. - Statically scoped enhancers and middleware classes that the module instantiates are included as well. - **Request-scoped** classes get **no** hooks, and neither does a class that becomes request-scoped by injecting one. They are created for each request and garbage-collected after the response, so they are not tied to the application lifecycle. - Transient providers instantiated at boot do receive them. How hooks are ordered across modules, and between providers that depend on one another, follows the import graph and each component's dependencies; that ordering is a subject of its own. ## Mistakes interviewers listen for - Claiming `onApplicationBootstrap()` runs after the server is listening; it runs before. - Expecting `SIGTERM` to trigger cleanup without `enableShutdownHooks()`. - Closing a connection in `onModuleDestroy()` that in-flight requests still use, when `onApplicationShutdown()` runs only after the server has closed. - Expecting hooks on a request-scoped provider.
- Does a NestJS class have to declare `implements OnModuleInit` for its hook to run?No. Nest checks at runtime whether the instance has a function named `onModuleInit` and calls it if so; TypeScript interfaces do not exist after compilation. Implementing the interface is still good practice, because the compiler then checks the method name and signature, and a typo such as `onModuleInt` would otherwise be silently ignored.
- Does `app.close()` in NestJS end the Node process?No. It runs `onModuleDestroy()`, `beforeApplicationShutdown()`, closes the server and other listeners, then runs `onApplicationShutdown()`. If an interval, an open socket or a background task is still alive, the process keeps running. With `enableShutdownHooks()`, the signal path is different: after the hooks Nest re-sends the signal to the process, which then ends.
- onApplicationBootstrap runs after the server has started listening.
- SIGTERM runs the shutdown hooks without any extra setup.
- Nest only calls a hook when the class declares the matching interface.
- Request-scoped providers get onModuleInit on every request.
- onApplicationShutdown runs while the HTTP server is still accepting requests.