0
0
NestjsConceptBeginner · 3 min read

What is Module in NestJS: Explanation and Example

In NestJS, a module is a class annotated with @Module() that organizes related components like controllers and providers. It acts like a container to group features and manage dependencies in a clear, modular way.
⚙️

How It Works

Think of a NestJS module like a room in a house where you keep related things together. For example, one room might be the kitchen with all cooking tools, and another room might be the living room with furniture. Similarly, a module groups related parts of your app, such as controllers (which handle requests) and providers (which contain business logic).

This grouping helps NestJS know what belongs together and how to connect different parts. When your app grows, modules keep it organized and easy to manage, just like rooms keep a house tidy.

💻

Example

This example shows a simple NestJS module that groups a controller and a service provider.

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

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

// cats.controller.ts
import { Controller, Get } from '@nestjs/common';
import { CatsService } from './cats.service';

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  findAll() {
    return this.catsService.findAll();
  }
}

// cats.service.ts
import { Injectable } from '@nestjs/common';

@Injectable()
export class CatsService {
  findAll() {
    return ['Cat 1', 'Cat 2', 'Cat 3'];
  }
}
Output
GET /cats returns ["Cat 1", "Cat 2", "Cat 3"]
🎯

When to Use

Use modules whenever you want to organize your NestJS app into clear sections. For example, if you have features like user management, products, or orders, create separate modules for each. This makes your code easier to read, test, and maintain.

Modules also help when you want to reuse parts of your app or share services between features. They are essential for scaling your app cleanly as it grows.

Key Points

  • A module is a class decorated with @Module().
  • It groups controllers and providers related to a feature.
  • Modules help organize and manage dependencies in your app.
  • They make your app scalable and maintainable.

Key Takeaways

A NestJS module groups related controllers and providers to organize your app.
Use @Module() decorator to define a module class.
Modules keep your app clean, scalable, and easy to maintain.
Create separate modules for different features or domains.
Modules manage dependencies and help NestJS connect parts of your app.