How to create modules and manage functionality

Learn about creating and managing NestJS modules.

overview

NestJS uses the concept of modules to organize the structure of your application and encourage code reuse. Modules group related controllers and services together to clarify the structure of your application. This article explains how to create and manage modules with concrete examples.

nest.js v10.1.7
nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

How to create a module

NestJS allows you to easily create modules using the CLI. Run the following command to create the users module.

nest g module users

Running this command will automatically create the necessary files for the users module.

src/
└── users/
    └── users.module.ts

Also, the created module is automatically added to the root module app.module.ts.

/src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from './users/users.module'; 

@Module({
  imports: [UsersModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

How to configure a module

Then add the controller and service to the users module. This makes the users module responsible for handling users.

/src/users/users.module.ts

import { Module } from '@nestjs/common';
import { UsersController } from './users.controller';
import { UsersService } from './users.service';

@Module({
  imports: [],
  controllers: [UsersController],
  providers: [UsersService],
})
export class UsersModule {}

The users module now has logic for manipulating user data. The root module app.module.ts looks like this:

/src/app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { UsersModule } from "./users/users.module";

@Module({
  imports: [UsersModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

By using modules in this way, you can group related functionality together and clarify the structure of your application.

summary

In this article, you learned how to create and manage modules in NestJS. Modules organize the structure of your application and encourage code reuse. As a next step, I recommend learning about NestJS middleware.