What is a module in NestJS?
A Module in NestJS is the fundamental building block of an application, grouping logically related pieces of code: controllers, services, providers, and other modules. It helps structure the project and makes the code modular, reusable, and easy to maintain.
A module's core idea
A module is a class with the @Module() decorator that tells NestJS:
- which components (controllers, services, providers) belong to this module;
- which dependencies it imports from other modules;
- which entities it exports outward.
A simple module example
javascript
import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';
@Module({
imports: [], // Import other modules
controllers: [UsersController], // Controllers (handle requests)
providers: [UsersService], // Services, Guards, Pipes, etc.
exports: [UsersService], // What's exposed to other modules
})
export class UsersModule {}This module combines UsersController and UsersService into a single logical area, working with users.
What a module contains
| Field | Purpose |
|---|---|
| imports | The list of other modules whose exported providers this module needs. |
| controllers | Classes that handle incoming requests (e.g. HTTP). |
| providers | Classes available via DI (services, guards, pipes, resolvers, repositories, etc.). |
| exports | What this module "hands out" for other modules to use. |
Why modules are needed
- Code organization
The project splits into independent areas:
UsersModule,AuthModule,ProductsModule, etc. - Reuse The same module can be imported in several places.
- Encapsulation Providers are only available within their own module by default, until you explicitly export them.
- Scalability Large projects can grow easily just by adding new modules.
The application's main module (AppModule)
Every NestJS application must have a root module, AppModule.
It wires in all the other modules:
javascript
import { Module } from '@nestjs/common';
import { UsersModule } from './users/users.module';
import { AuthModule } from './auth/auth.module';
@Module({
imports: [UsersModule, AuthModule],
})
export class AppModule {}An example project structure
javascript
src/
├── app.module.ts ← the root module
├── users/
│ ├── users.module.ts ← the users module
│ ├── users.controller.ts
│ └── users.service.ts
├── auth/
│ ├── auth.module.ts ← the auth module
│ ├── auth.controller.ts
│ └── auth.service.tsSummary
| Key idea | Description |
|---|---|
| A module is a container for code | It groups everything related to one piece of functionality |
| Every Nest application is made of modules | The root AppModule wires in the rest |
| Encapsulation and reuse | A module hides its internal details and exposes an interface via exports |
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.