Feature Modules
A feature module packages everything for one domain area, like users or orders.
A feature module owns one area of your application - users, orders, billing. It bundles that feature's controller, service, and DTOs so the feature is self-contained.
Wiring it up
You create the feature module, then import it into AppModule. This keeps the root module small: it simply lists the features that make up the app.
The Nest CLI encourages this pattern - nest g module users creates the module and imports it into the root for you.
Example
// app.module.ts
import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
import { OrdersModule } from './orders/orders.module';
@Module({
imports: [UsersModule, OrdersModule],
})
export class AppModule {}When to use it
- A team creates an OrdersModule that encapsulates OrdersController, OrdersService, and OrdersRepository so the Orders feature is independently deployable as a microservice later.
- A developer generates a full AuthModule with `nest g module auth` then adds AuthController and AuthService inside it without touching other modules.
- An architect requires that all cross-feature communication goes through exported services, enforcing a clean API boundary at the module level.
More examples
Feature module scaffold
Shows how the CLI creates a self-contained feature folder in three commands.
nest g module orders
nest g controller orders --no-spec
nest g service orders --no-spec
# Result: src/orders/ with orders.module.ts,
# orders.controller.ts, orders.service.tsFeature module class
Defines the OrdersModule with its controller and service, exporting the service for cross-module use.
import { Module } from '@nestjs/common';
import { OrdersController } from './orders.controller';
import { OrdersService } from './orders.service';
@Module({
controllers: [OrdersController],
providers: [OrdersService],
exports: [OrdersService], // allow other modules to use OrdersService
})
export class OrdersModule {}Importing feature module in AppModule
Registers both feature modules in AppModule so all their controllers and providers are active in the application.
import { Module } from '@nestjs/common';
import { OrdersModule } from './orders/orders.module';
import { UsersModule } from './users/users.module';
@Module({
imports: [UsersModule, OrdersModule],
})
export class AppModule {}
Discussion