Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NestJs order of initialization

I am studying NestJS and i have one question about the order of initialization in NestJs. When a NestJS application get bootstraped, in what order does the dependencies get created ? Module first or provider first or controller first ?

I try to read NestJs documentation but it wasn't clear enough.

like image 450
Huynh Nguyen Avatar asked Oct 24 '25 14:10

Huynh Nguyen


1 Answers

NestJS simply using top-down approach, the explaination is :

Module initialization

When a NestJS application is bootstrapped, it begins by initializing the root module, which then initializes any imported modules in a recursive manner. This means that modules are initialized in a top-down fashion, with the root module being the first to initialize, followed by any imported modules.

Provider registration

Once all the modules are initialized, the next step is to register the providers. Providers are registered within each module, and they can be used across the module hierarchy. Providers can be defined in two ways - either as a class with the @Injectable() decorator or as a value (e.g. string, number) using the @Inject() decorator.

Controller initialization

Finally, after all providers have been registered, controllers are initialized. Controllers are responsible for handling incoming requests and returning responses, and they can make use of providers to handle the request logic.

Breaking Down

breaking down you can find using NEST_DEBUG=true from your ENV variable

Note

you can hook also such as the onModuleInit() method in modules or the onModuleInit()

like image 116
Abdul Aziz Al Basyir Avatar answered Oct 27 '25 05:10

Abdul Aziz Al Basyir