What is the difference between forRoot() and forFeature() in NestJS modules?
Answer
This pattern (used by TypeORM, Bull, Config modules) separates global configuration from feature-specific registration. forRoot() is called once in AppModule — it configures the module's global settings (database connection parameters, Redis URL) and makes the module available globally. It is typically implemented using the @Global() decorator. forFeature() is called in feature modules to register specific entities, queues, or configurations for that feature: TypeOrmModule.forFeature([User, Post]) makes Repository<User> injectable in that module. Internally, these are static factory methods that return DynamicModule — a module whose metadata is computed at runtime rather than being static decorator metadata.
Previous
What is custom provider syntax in NestJS (useClass, useValue, useFactory)?
Next
How do you implement health checks in NestJS?
More NestJS Questions
View all →- Advanced What is the CQRS pattern and how does NestJS support it?
- Advanced How do you implement gRPC in NestJS?
- Advanced What is the NestJS Interceptor execution order and how do multiple interceptors interact?
- Advanced How does NestJS handle graceful shutdown?
- Advanced What is custom provider syntax in NestJS (useClass, useValue, useFactory)?