🦅 NestJS Advanced

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.