Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 42 ยท Controllers and Routing

Modules

Learn how NestJS modules group controllers and providers, how imports and exports control visibility, and when to use shared, global and re-exporting modules.

A NestJS application is a tree of modules. A module is a class decorated with @Module() that says which controllers handle requests, which providers (services and other injectables) exist, which other modules it needs, and which of its own providers it is willing to share. Every app has at least one module, the root module, and real apps have dozens.

Modules matter because they draw boundaries. By default a provider is private to the module that declares it, so a feature can keep its internals hidden and publish only a small, deliberate surface. This lesson builds on controllers and providers and dependency injection: controllers and providers are the things, and modules decide who can see what.

The real Nest code below is read-only, because the framework needs Node and npm. At the end you can run a stand-in that applies the same visibility rules in plain JavaScript, so you can see why an injection fails or succeeds. Where the stand-in simplifies something, it says so.

The four properties of @Module()

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

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

The decorator takes an object with four optional arrays:

Property What goes in it Effect
providers Classes (or custom provider objects) that Nest should instantiate Available for injection inside this module
controllers Controller classes Their routes are registered
imports Other modules whose exported providers you need Their exports become injectable here
exports A subset of this module's providers, or modules it re-exports Visible to modules that import this one

Nothing here is automatic. A class with @Injectable() that is not listed in some module's providers is not part of the app, and injecting it fails at startup with an error such as "Nest can't resolve dependencies of the UsersService (?)". The message names the class, the position of the missing argument and the module in which the lookup happened.

A module is a boundary

providers What this module creates.
controllers What answers requests.
imports What it borrows from others.
exports What it shares in return.

Anything not exported stays private.

1 / 2

Feature modules

The usual way to organize an app is one module per feature: UsersModule, OrdersModule, BillingModule. Each contains its own controller, service and data-access code. The root module then lists the features:

TypeScript
@Module({
  imports: [UsersModule, OrdersModule, BillingModule],
})
export class AppModule {}

The CLI helps: nest generate module users creates the file and adds it to the nearest module's imports array. Keeping a feature in one folder with one module means you can read, test and even extract it without chasing files across the project.

A module is a singleton. If ten modules import DatabaseModule, Nest creates it, and the providers inside it, once, and all ten share that instance. This is why a database connection pool or a cache declared in one module can safely be used from many places.

Exports and imports

Suppose OrdersService needs UsersService. Two things must be true:

  1. UsersModule lists UsersService in exports.
  2. OrdersModule lists UsersModule in imports.

Miss either one and injection fails. Forgetting exports is the most common mistake for beginners, because the code compiles perfectly and fails only when the app starts. Importing a module does not give you its private providers, only what it exports.

You never provide the same class in two modules just to make an error go away. Doing so creates two separate instances, which breaks anything that relies on shared state, such as a cache or a connection. Export from one module and import it instead.

Re-exporting modules

A module can export another module. Everything that module exports then flows through to your importers. This is handy for a "bundle" module that groups infrastructure:

TypeScript
@Module({
  imports: [DatabaseModule, ConfigModule],
  exports: [DatabaseModule, ConfigModule],
})
export class CoreModule {}

Any module that imports CoreModule now also sees what DatabaseModule and ConfigModule export. Use this sparingly: a bundle hides where things really come from, which makes the dependency graph harder to read.

Shared and global modules

Because modules are singletons, every module that imports DatabaseModule already shares the same instance. That is the normal way of sharing, and it needs no special syntax.

For things needed almost everywhere, such as logging or configuration, importing the module in dozens of places is tedious. The @Global() decorator makes a module's exports available everywhere once the module is registered (usually in the root module):

TypeScript
import { Global, Module } from '@nestjs/common';

@Global()
@Module({
  providers: [AppLogger],
  exports: [AppLogger],
})
export class LoggingModule {}

A global module still has to export what it shares. Global does not mean "everything is public"; it only removes the need to import.

Be careful with this convenience. Global modules hide dependencies, because a service can use AppLogger without any trace of where it came from. Keep the list short, and prefer explicit imports for business features. Configuration is covered in Configuration and Environment, and modules that take options are covered in Dynamic Modules and Provider Scopes.

Modules can inject too

A module class can have a constructor with injected providers, for example to run setup code when the app boots:

TypeScript
@Module({ providers: [CatsService] })
export class CatsModule {
  constructor(private readonly catsService: CatsService) {}
}

Module classes cannot themselves be injected into providers, because of circular dependency concerns. If two modules truly depend on each other, Nest offers forwardRef(), but a circular import is usually a hint that a third module should hold the shared part.

Stand-in: visibility rules in plain JavaScript

The first stand-in is not Nest. It models modules as plain objects with imports, providers, exports and a global flag, and computes which providers each module can see. It also follows re-exports (an entry in exports that names a module). The result matches the rules above; the real framework adds instance creation, lifecycle hooks and error messages on top.

JS Which providers can each module see?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at Orders: it imports only Core, yet it sees UsersService and DbService, because Core re-exports the modules that export them. It does not see PasswordHasher, which Users never exported. Reports imports nothing, so it sees only its own provider and the global Logger.

Stand-in: catching a missing import at startup

The second stand-in checks each provider's constructor dependencies against what its module can see, and prints a message in the spirit of Nest's. It then fixes the problem by adding one import. The message text is simplified, not the framework's exact wording.

JS Resolving dependencies like the injector

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The fix is always the same pair of edits: make sure the owner exports the provider, and make sure the consumer imports the owner.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A provider is listed in UsersModule providers but not in its exports. What happens when OrdersModule imports UsersModule and injects that provider?

    Providers are private by default. An importing module sees only what the imported module lists in exports, and Nest reports an unresolved dependency when the app boots.
  2. 2. What does @Global() on a module change?

    A global module still has to export what it shares. The only thing that changes is that other modules no longer need to list it in imports.
  3. 3. Why should you avoid adding the same service to the providers of two modules just to share it?

    A module owns the instances of its providers. Export the service from one module and import that module elsewhere so there is a single instance.
  4. 4. A CoreModule imports DatabaseModule and lists DatabaseModule in its own exports. What does that do?

    Exporting a module re-exports everything that module exports, which is how bundle modules work.

Summary

  • @Module() groups providers, controllers, imports and exports; providers are private unless exported.
  • To share a service: the owner exports it, the consumer imports the owner.
  • Modules are singletons, so a shared provider has one instance across the app.
  • A module can re-export other modules to bundle them for its importers.
  • @Global() removes the need for imports but not the need for exports; use it for a few infrastructure modules only.
  • Organize by feature: one module per feature folder, listed in the root module.

Next, learn how to run code before a request reaches your controller in Middleware.