DEV Community

Cover image for Understanding NestJS Modules
Tasfia Islam
Tasfia Islam

Posted on

Understanding NestJS Modules

What is a module?

In NestJS, a module is a class which helps to organize other building blocks of the application like components, services etc. maintaining modularity with separate concerns.

Modules serve several key purposes in NestJS development.

Each module provides encapsulation and isolation to a closely related set of capabilities. This isolation helps to avoid naming conflicts and provides an effective way to organize the components.

A module class define providers and inject them into other components leveraging Dependency Injection.

Modules create way of reusability and scalability across the components and across projects and can also be nested within other modules creating a hierarchical structure.

An example module

Let's create a basic Module.

import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';

@Module({
  controllers: [UserController],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}
Enter fullscreen mode Exit fullscreen mode

In this example UserModule encapsulates the UserService and UserController.

Seems confusing? Let's break down the parts of the module.

Breakdown of a module

decorators
We use the @Module decorator to create a module which takes a single object defining the module's properties.

providers
The provider that can be shared across other parts of the application and handles specific business logic and consists of service and other reusable components.

controllers
The set of Controllers which define end points and route handlers.

imports
The list of imported modules that export the providers required in this module.

exports
Modules export components available to be used outside the module.

Conclusion

Modules are the backbone of a reusable and well structured NestJS application enabling us to create well-organized, scalable and modular codebases. This was a brief introduction to modules.

Read more from the official documentation

Top comments (0)