Back to the blog

NestJS: modules don't guarantee a modular architecture

nestjstypescriptarchitecture

Why splitting files into modules doesn't solve coupling and how to think about the boundaries of the application.

The initial ease

NestJS encourages controllers, providers and modules. That structure helps a lot, but it can also give the feeling that any project organized into folders already has architectural boundaries.

Dependency matters more than folder

If the orders module directly accesses internal repositories of users, payments and inventory, the boundaries are only visual. I prefer to expose use cases or small contracts and keep domain entities independent of decorators when that brings a real benefit in testing and portability.

A common symptom of this problem is a service directly accessing other domains' repositories:

@Injectable()
export class OrdersService {
  constructor(
    private readonly ordersRepository: OrdersRepository,
    private readonly usersRepository: UsersRepository,
    private readonly paymentsRepository: PaymentsRepository,
    private readonly inventoryRepository: InventoryRepository,
  ) {}

  async createOrder(dto: CreateOrderDto) {
    const user = await this.usersRepository.findById(dto.userId);
    const inStock = await this.inventoryRepository.hasStock(dto.productId);
    if (!inStock) throw new BadRequestException('out of stock');

    await this.paymentsRepository.charge(user.id, dto.amount);
    return this.ordersRepository.save(dto);
  }
}

OrdersService knows the internal schema of the users, payments and inventory modules — any change to them ripples back here. The path I prefer is to expose a use case with small contracts, keeping the domain entity free of decorators:

interface FindUser {
  findById(userId: string): Promise<User>;
}

interface CheckInventory {
  hasStock(productId: string): Promise<boolean>;
}

interface ChargeCustomer {
  charge(userId: string, amount: number): Promise<void>;
}

@Injectable()
export class CreateOrder {
  constructor(
    private readonly findUser: FindUser,
    private readonly checkInventory: CheckInventory,
    private readonly chargeCustomer: ChargeCustomer,
    private readonly ordersRepository: OrdersRepository,
  ) {}

  async execute(input: CreateOrderInput): Promise<Order> {
    const user = await this.findUser.findById(input.userId);
    const inStock = await this.checkInventory.hasStock(input.productId);
    if (!inStock) throw new OutOfStockError(input.productId);

    await this.chargeCustomer.charge(user.id, input.amount);

    const order = Order.create(input);
    return this.ordersRepository.save(order);
  }
}

The concrete implementations of FindUser, CheckInventory and ChargeCustomer are still resolved by NestJS's injection container — behind a token provider, for example —, but CreateOrder only sees the contracts, not the users, inventory or payments modules behind them.

The injection container should assemble the dependencies. It doesn't need to appear in every rule. Global providers and circular imports are signs that responsibilities may be crossing the modules without a clear contract.

Pragmatism

Not every API needs multiple layers. For simple operations, controller, service and repository may be enough. The architecture should grow as there are invariants, integrations and different rhythms of change, not to fulfill an abstract design.

Conclusion for now

NestJS offers good organization tools, but modularity comes from the dependencies that are allowed. A module is useful when it can explain what it offers and what it needs without exposing all of its details.