Module Metadata

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

The @Module() decorator takes a single object whose properties describe the module.

Overview

Every Nest application is constructed from modules. The root module is the starting point Nest uses to build the application graph (the internal data structure Nest uses to resolve module and provider relationships and dependencies).

The @Module() decorator defines a module by providing metadata to the Nest IoC container.

Key Concepts

The metadata object passed to the @Module() decorator has four main properties:

  • providers: The array of providers (services, repositories, factories) that will be instantiated by the Nest injector and that may be shared across this module.
  • controllers: The set of controllers defined in this module which have to be instantiated to handle incoming HTTP requests.
  • imports: The list of imported modules that export the providers which are required in this module.
  • exports: The subset of providers that are provided by this module and should be available in other modules which import this module.

Code Examples

A Standard Module Configuration

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

@Module({
  // 1. We need providers from the DatabaseModule
  imports: [DatabaseModule],
  
  // 2. We need to expose the CatsController to handle HTTP requests
  controllers: [CatsController],
  
  // 3. We need to instantiate the CatsService
  providers: [CatsService],
  
  // 4. We want to allow other modules to inject the CatsService
  exports: [CatsService]
})
export class CatsModule {}

Module Re-exporting

A module can export modules that it imports. This is useful for creating a “Core” module that bundles common dependencies.

@Module({
  imports: [CommonModule],
  exports: [CommonModule],
})
export class CoreModule {}

Best Practices

  • Strict Exports: Only export providers that are explicitly meant to be used by other modules. Keep internal helper services private (don’t add them to the exports array) to enforce encapsulation.
  • Don’t Export Controllers: Controllers should never be exported or injected. They handle HTTP traffic, they don’t provide business logic to other classes.