0
0
NestJSframework~5 mins

Root module (AppModule) in NestJS

Choose your learning style9 modes available
Introduction

The root module (AppModule) is the main starting point of a NestJS application. It organizes and connects all parts of the app.

When starting a new NestJS project to set up the main structure.
When you want to register controllers and providers globally.
When you need to import other feature modules into your app.
When configuring global services like database or configuration.
When defining the entry point for the NestJS application.
Syntax
NestJS
import { Module } from '@nestjs/common';

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

The @Module decorator defines metadata for the module.

imports is for other modules to include.

controllers handle incoming requests.

providers are services or helpers used in the app.

Examples
This example shows a root module with one controller and one service registered.
NestJS
import { Module } from '@nestjs/common';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
  controllers: [CatsController],
  providers: [CatsService],
})
export class AppModule {}
This example imports another module (DatabaseModule) into the root module.
NestJS
import { Module } from '@nestjs/common';
import { DatabaseModule } from './database.module';

@Module({
  imports: [DatabaseModule],
})
export class AppModule {}
Sample Program

This simple root module has one controller that responds with a greeting message at the root URL.

NestJS
import { Module, Controller, Get } from '@nestjs/common';

@Controller()
class AppController {
  @Get()
  getRoot() {
    return 'Hello from AppModule!';
  }
}

@Module({
  controllers: [AppController],
  providers: [],
})
export class AppModule {}
OutputSuccess
Important Notes

The root module is required for every NestJS app.

You can split your app into many feature modules and import them here.

Keep the root module clean by moving logic to other modules when the app grows.

Summary

The root module (AppModule) is the main module that starts your NestJS app.

It uses the @Module decorator to organize controllers, providers, and imports.

It connects all parts of your app and defines the app's structure.