Feature Modules

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 10 min

Feature modules simply organize code relevant for a specific feature, keeping code organized and establishing clear boundaries.

Overview

As an application grows, managing all controllers and providers in the root AppModule becomes impossible. NestJS strongly encourages splitting your application into smaller, domain-specific modules called “Feature Modules”.

A Feature Module encapsulates all the logic related to a specific domain (e.g., Users, Orders, Products, Authentication).

Key Concepts

  • Encapsulation: A feature module encapsulates its own controllers, services, and entities.
  • Folder Structure: Typically, a feature module lives in its own directory, containing all files related to that feature (e.g., src/cats/cats.module.ts, src/cats/cats.controller.ts, src/cats/cats.service.ts).
  • Integration: Feature modules are then imported into the root AppModule to be registered with the framework.

Code Examples

The Feature Module (cats.module.ts)

import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
  controllers: [CatsController],
  providers: [CatsService],
  // Exporting CatsService allows other modules to use it
  exports: [CatsService] 
})
export class CatsModule {}

The Root Module (app.module.ts)

import { Module } from '@nestjs/common';
import { CatsModule } from './cats/cats.module';
import { DogsModule } from './dogs/dogs.module';

@Module({
  // Importing feature modules bundles them into the final app graph
  imports: [CatsModule, DogsModule],
})
export class AppModule {}

Best Practices

  • Domain-Driven Design (DDD): Organize feature modules around business domains, not technical layers. A UsersModule is better than a ControllersModule and a ServicesModule.
  • The Nest CLI: Use the Nest CLI to generate feature modules quickly and consistently: nest g module cats (generates the module) and nest g resource cats (generates a full CRUD module with controller, service, DTOs, and entities).