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
@Moduledecorator, 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:
| Property | Purpose |
|---|---|
| imports | List other modules to include |
| controllers | List controllers handling requests |
| providers | List services or providers to inject |
| exports | List 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.