This document describes the application context structure and lifecycle management in NestJS, covering how applications are created, initialized, and terminated. This includes the bootstrapping process, lifecycle hooks, and shutdown mechanisms.
For information about dependency injection mechanics, see Dependency Injection System. For module structure and organization, see Module System.
NestJS provides three main application context types, each serving different use cases while sharing a common foundation.
Sources: packages/core/nest-application-context.ts40-512 packages/core/nest-application.ts54-497 packages/microservices/nest-microservice.ts35-299
The base context class providing core functionality for all application types.
| Property | Type | Purpose |
|---|---|---|
container | NestContainer | Holds all modules, providers, controllers |
injector | Injector | Resolves dependencies and creates instances |
isInitialized | boolean | Tracks initialization state |
moduleCompiler | ModuleCompiler | Compiles module metadata |
Key Methods:
select<T>(module) - Navigate to a specific module contextget<T>(typeOrToken) - Retrieve a singleton instanceresolve<T>(typeOrToken, contextId) - Resolve a request-scoped instanceinit() - Initialize the application and call lifecycle hooksclose() - Terminate the application gracefullySources: packages/core/nest-application-context.ts68-81
Extends NestApplicationContext with HTTP server capabilities.
Additional features:
Sources: packages/core/nest-application.ts54-109
Extends NestApplicationContext for microservice patterns.
Additional features:
Sources: packages/microservices/nest-microservice.ts35-82
The NestFactory class orchestrates the entire bootstrapping process.
Sources: packages/core/nest-factory.ts201-248
1. Container Creation
The NestContainer is initialized with application configuration:
packages/core/nest-factory.ts88-90
2. Module Scanning
DependenciesScanner recursively scans modules, starting from the root module:
@Module() decoratorspackages/core/scanner.ts86-104
3. Instance Loading
InstanceLoader creates instances of all registered providers and controllers:
packages/core/injector/instance-loader.ts27-82
Sources: packages/core/nest-factory.ts59-113 packages/core/scanner.ts75-104 packages/core/injector/instance-loader.ts18-82
After bootstrapping, the application must be initialized via init() before it can handle requests.
Sources: packages/core/nest-application.ts176-197 packages/core/nest-application-context.ts253-271
Phase 1: HTTP Adapter Initialization
packages/core/nest-application.ts182
Phase 2: Body Parser Registration
packages/core/nest-application.ts186-199
Phase 3: Module Registration
Registers WebSocket, microservice, and middleware modules:
packages/core/nest-application.ts139-161
Phase 4: Router Registration
Routes are registered with the HTTP adapter:
packages/core/nest-application.ts205-211
Phase 5: Lifecycle Hooks
onModuleInit hooks are calledonApplicationBootstrap hooks are calledpackages/core/nest-application.ts190-192
Sources: packages/core/nest-application.ts176-197
NestJS provides five lifecycle hooks that providers, controllers, and modules can implement.
Sources: packages/core/nest-application-context.ts422-480
| Hook | Interface | Timing | Use Case |
|---|---|---|---|
onModuleInit | OnModuleInit | After all dependencies resolved | Initialize module-specific logic |
onApplicationBootstrap | OnApplicationBootstrap | After all modules initialized | Perform application-wide setup |
onModuleDestroy | OnModuleDestroy | Before module cleanup | Clean up module resources |
beforeApplicationShutdown | BeforeApplicationShutdown | Before connections closed | Prepare for shutdown |
onApplicationShutdown | OnApplicationShutdown | After connections closed | Final cleanup |
Modules are assigned a "distance" value representing their depth in the module dependency tree. This determines hook execution order:
Number.MAX_VALUE to ensure they initialize firstpackages/core/scanner.ts397-416
Hook Invocation Implementation:
The getModulesToTriggerHooksOn() method sorts modules by distance:
packages/core/nest-application-context.ts490-504
For initialization:
For shutdown:
packages/core/nest-application-context.ts422-441
Sources: packages/core/scanner.ts397-416 packages/core/nest-application-context.ts422-504
NestJS supports graceful shutdown through process signals and explicit close methods.
Default Signals:
SIGTERMSIGINTSIGHUPSIGBREAK (Windows)packages/core/nest-application-context.ts324-346
Sources: packages/core/nest-application-context.ts277-284 packages/core/nest-application-context.ts361-404
The shutdown listener is registered for each signal:
packages/core/nest-application-context.ts361-404
Cleanup Process:
onModuleDestroy() on all modulesbeforeApplicationShutdown(signal) with signal nameonApplicationShutdown(signal) for final cleanupprocess.exit(0) or process.kill(process.pid, signal)packages/core/nest-application.ts97-108
Sources: packages/core/nest-application-context.ts277-284 packages/core/nest-application-context.ts361-404 packages/core/nest-application.ts97-108
The application context provides methods to navigate the module tree and retrieve instances.
The select() method navigates to a specific module:
Module Token Resolution:
packages/core/nest-application-context.ts92-130
The select() method:
ModuleTokenFactoryNestApplicationContext scoped to that moduleSources: packages/core/nest-application-context.ts92-130
| Method | Scope | Returns | Use Case |
|---|---|---|---|
get<T>(token) | Singleton | Single instance | Retrieve DEFAULT scope providers |
get<T>(token, {strict: true}) | Current module only | Single instance | Strict module boundary |
get<T>(token, {each: true}) | All modules | Array of instances | Multiple registrations |
resolve<T>(token) | REQUEST scope | New instance | Request-scoped providers |
resolve<T>(token, contextId) | Custom context | Scoped instance | Custom DI context |
Get Method Implementation:
packages/core/nest-application-context.ts136-175
Resolve Method Implementation:
packages/core/nest-application-context.ts181-237
The resolve() method:
ContextId if not providedresolvePerContext() to get a request-scoped instanceSources: packages/core/nest-application-context.ts136-237
Each request can have its own DI context via ContextId:
packages/core/injector/instance-wrapper.ts36-40
The registerRequestByContextId() method associates a request object with a context:
packages/core/nest-application-context.ts243-245
This enables REQUEST-scoped providers to access the current request object.
Sources: packages/core/injector/instance-wrapper.ts36-40 packages/core/nest-application-context.ts243-245
NestJS supports a "preview mode" where providers are not instantiated but the module structure is built.
Preview Mode Behavior:
initOnPreview: true)packages/core/nest-application-context.ts78-80
Modules can be marked to initialize even in preview mode:
packages/core/injector/container.ts163-169
This is useful for core infrastructure modules that must always initialize.
Sources: packages/core/nest-application-context.ts78-80 packages/core/nest-application-context.ts482-488 packages/core/nest-application-context.ts500-502 packages/core/injector/container.ts163-169
The context relies on several internal components working together.
Sources: packages/core/nest-application-context.ts68-81 packages/core/injector/container.ts31-60 packages/core/injector/module.ts44-160
NestContainer
Central registry for all modules and configuration:
Module instances in ModulesContaineraddModule(), addProvider(), addImport() methodspackages/core/injector/container.ts31-60
Module
Represents a single module with its providers and controllers:
ModuleRef for dependency retrievalpackages/core/injector/module.ts44-160
Injector
Handles dependency resolution and instantiation:
instantiateClass()packages/core/injector/injector.ts86-107
InstanceWrapper
Wraps each provider/controller instance with metadata:
isResolved, isPending)packages/core/injector/instance-wrapper.ts61-98
Sources: packages/core/injector/container.ts31-60 packages/core/injector/module.ts44-160 packages/core/injector/injector.ts86-107 packages/core/injector/instance-wrapper.ts61-98
The sample application at sample/18-context demonstrates practical context usage patterns.
Key Dependencies:
sample/18-context/package.json21-26
This sample illustrates:
Sources: sample/18-context/package.json1-48
Refresh this wiki