0
0
NestjsHow-ToBeginner ยท 3 min read

How to Use @Module Decorator in NestJS: Simple Guide

In NestJS, use the @Module decorator to define a module that groups related controllers, providers, and imports. It organizes your app into cohesive blocks by specifying imports, controllers, providers, and exports inside the decorator.
๐Ÿ“

Syntax

The @Module decorator takes an object with these main properties:

  • imports: Other modules to include.
  • controllers: Controllers to handle incoming requests.
  • providers: Services or providers to inject.
  • exports: Providers to share with other modules.
typescript
import { Module } from '@nestjs/common';

@Module({
  imports: [],
  controllers: [],
  providers: [],
  exports: [],
})
export class YourModule {}
๐Ÿ’ป

Example

This example shows a simple module with one controller and one service. The @Module decorator groups them together so NestJS knows how to build the app.

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

@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}
Output
No direct output; NestJS uses this module to organize app components.
โš ๏ธ

Common Pitfalls

Common mistakes include:

  • Forgetting to add controllers or providers inside the @Module decorator, so NestJS can't find them.
  • Not importing dependent modules in imports, causing injection errors.
  • Trying to use providers without exporting them if they are needed in other modules.
typescript
/* Wrong: Missing provider in module */
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';

@Module({
  controllers: [CatsController],
  // providers: [CatsService], // Forgot this line
})
export class CatsModule {}

/* Right: Include provider */
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}
๐Ÿ“Š

Quick Reference

Use this quick guide to remember the @Module decorator parts:

PropertyPurpose
importsList other modules to include
controllersList controllers handling requests
providersList services or providers to inject
exportsList providers to share with other modules
โœ…

Key Takeaways

Use @Module to group related controllers and providers in NestJS.
Always list controllers and providers inside the @Module decorator.
Import dependent modules in the imports array to use their exports.
Export providers if other modules need to use them.
Missing providers or imports causes injection errors.