Skip to main content

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

FieldPurpose
importsThe list of other modules whose exported providers this module needs.
controllersClasses that handle incoming requests (e.g. HTTP).
providersClasses available via DI (services, guards, pipes, resolvers, repositories, etc.).
exportsWhat this module "hands out" for other modules to use.

Why modules are needed

  1. Code organization The project splits into independent areas: UsersModule, AuthModule, ProductsModule, etc.
  2. Reuse The same module can be imported in several places.
  3. Encapsulation Providers are only available within their own module by default, until you explicitly export them.
  4. 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.ts

Summary

Key ideaDescription
A module is a container for codeIt groups everything related to one piece of functionality
Every Nest application is made of modulesThe root AppModule wires in the rest
Encapsulation and reuseA module hides its internal details and exposes an interface via exports

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.