Bird
Raised Fist0
NestJSframework~10 mins

Shared modules in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Shared modules
Create Shared Module
↓
Declare Providers
↓
Export Providers
↓
Import Shared Module in Feature Modules
↓
Use Shared Providers
↓
Single Instance Across App
This flow shows how a shared module is created with providers, exports them, and then feature modules import it to use the same instances.
Execution Sample
NestJS
import { Module } from '@nestjs/common';
import { LoggerService } from './logger.service';

@Module({
  providers: [LoggerService],
  exports: [LoggerService],
})
export class SharedModule {}
Defines a shared module that provides and exports LoggerService for reuse.
Execution Table
StepActionModule StateProviders AvailableExports AvailableEffect
1Define SharedModule with LoggerService providerSharedModule createdLoggerServiceNone yetModule ready with provider
2Export LoggerService from SharedModuleSharedModule updatedLoggerServiceLoggerServiceLoggerService can be used outside
3Import SharedModule in FeatureModuleFeatureModule createdLoggerService (from SharedModule)NoneFeatureModule can access exported providers
4FeatureModule uses LoggerServiceFeatureModule runningLoggerService (from SharedModule)NoneSingle LoggerService instance shared
5Another FeatureModule imports SharedModuleAnother FeatureModule createdLoggerService (from SharedModule)NoneAlso shares LoggerService instance
6App runs with shared LoggerServiceApp runningLoggerService sharedLoggerServiceSingle instance used app-wide
💡 All feature modules share the same exported providers from SharedModule, ensuring single instances.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
SharedModule.providers[][LoggerService][LoggerService][LoggerService][LoggerService][LoggerService]
SharedModule.exports[][][LoggerService][LoggerService][LoggerService][LoggerService]
FeatureModule.providers[][][][][][]
FeatureModule.imports[][][SharedModule][SharedModule][SharedModule][SharedModule]
Key Moments - 3 Insights
Why do we export providers in the shared module?
Exporting providers (see step 2 in execution_table) makes them available to other modules that import the shared module. Without export, other modules cannot use those providers.
Does importing the shared module create new instances of providers each time?
No. As shown in steps 4 and 5, importing the shared module shares the same instance of providers across modules, avoiding duplication.
Can feature modules use providers from the shared module without importing it?
No. Feature modules must import the shared module (step 3) to access its exported providers.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, at which step is LoggerService made available to other modules?
AStep 1
BStep 2
CStep 4
DStep 3
💡 Hint
Check the 'Exports Available' column to see when LoggerService is exported.
According to variable_tracker, what is the state of FeatureModule.providers after step 4?
A[SharedModule]
B[LoggerService]
C[]
Dundefined
💡 Hint
Look at the FeatureModule.providers row under 'After Step 4' column.
If SharedModule did not export LoggerService, what would happen when FeatureModule tries to use it?
AFeatureModule would not have access to LoggerService
BLoggerService would be shared anyway
CFeatureModule would get its own LoggerService instance
DApp would crash immediately
💡 Hint
Refer to key_moments about exporting providers and step 2 in execution_table.
Concept Snapshot
Shared modules in NestJS:
- Create a module with providers
- Export providers to share them
- Import shared module in feature modules
- Providers are singletons shared app-wide
- Without export, providers are private
- Enables clean, reusable code
Full Transcript
In NestJS, a shared module is a module that provides services or providers that multiple other modules can use. First, you create the shared module and declare providers inside it. Then, you export those providers so other modules can access them. Feature modules import the shared module to use the exported providers. This sharing ensures a single instance of each provider is used across the app, avoiding duplication. If providers are not exported, other modules cannot use them. This pattern helps keep code clean and reusable by centralizing common services.

Practice

(1/5)
1. What is the main purpose of a Shared Module in NestJS?
easy
A. To define database entities
B. To create a new controller for handling requests
C. To share providers and services across multiple modules
D. To configure middleware for the application

Solution

  1. Step 1: Understand the role of Shared Modules

    Shared modules are designed to hold providers and services that can be reused in different parts of the app.
  2. Step 2: Compare with other module roles

    Controllers handle requests, entities define data models, and middleware configures request handling, which are not the main purpose of shared modules.
  3. Final Answer:

    To share providers and services across multiple modules -> Option C
  4. Quick Check:

    Shared modules = share providers [OK]
Hint: Shared modules share providers, not controllers or entities [OK]
Common Mistakes:
  • Confusing shared modules with controllers
  • Thinking shared modules define database entities
  • Assuming shared modules configure middleware
2. Which of the following is the correct way to export a provider from a shared module in NestJS?
easy
A. Add the provider to the exports array in the module decorator
B. Add the provider to the controllers array
C. Add the provider to the imports array
D. Add the provider to the bootstrap array

Solution

  1. Step 1: Recall module decorator properties

    Providers are shared by listing them in the exports array of the module decorator.
  2. Step 2: Understand other arrays

    controllers is for controllers, imports is for importing other modules, and bootstrap is not used in modules.
  3. Final Answer:

    Add the provider to the exports array in the module decorator -> Option A
  4. Quick Check:

    Export providers via exports array [OK]
Hint: Use exports array to share providers [OK]
Common Mistakes:
  • Putting providers in controllers array
  • Confusing imports with exports
  • Using bootstrap array which doesn't exist in modules
3. Given this shared module code, what will be the output when AppModule injects CommonService and calls getMessage()?
import { Module } from '@nestjs/common';
import { CommonService } from './common.service';

@Module({
  providers: [CommonService],
  exports: [CommonService],
})
export class SharedModule {}

// CommonService
export class CommonService {
  getMessage() {
    return 'Hello from SharedModule';
  }
}

// AppModule
import { Module } from '@nestjs/common';
import { SharedModule } from './shared.module';

@Module({
  imports: [SharedModule],
})
export class AppModule {
  constructor(private commonService: CommonService) {}

  printMessage() {
    console.log(this.commonService.getMessage());
  }
}
medium
A. Error: CommonService not found
B. Undefined
C. Hello from SharedModule
D. Hello from AppModule

Solution

  1. Step 1: Check provider export and import

    SharedModule exports CommonService, and AppModule imports SharedModule, so CommonService is available in AppModule.
  2. Step 2: Understand service method call

    Calling getMessage() returns the string 'Hello from SharedModule'.
  3. Final Answer:

    Error: CommonService not found -> Option A
  4. Quick Check:

    Service must be injected via constructor and registered as provider [OK]
Hint: Import shared module to access exported services [OK]
Common Mistakes:
  • Forgetting to export the provider
  • Not importing the shared module in AppModule
  • Assuming service returns undefined
4. Identify the error in this shared module setup:
import { Module } from '@nestjs/common';
import { LoggerService } from './logger.service';

@Module({
  providers: [LoggerService],
  imports: [LoggerService],
  exports: [LoggerService],
})
export class LoggerModule {}
medium
A. LoggerService must be declared as a global provider
B. LoggerService should not be in the imports array
C. LoggerService should not be exported
D. LoggerService must be in controllers array

Solution

  1. Step 1: Review module decorator arrays

    The imports array is for importing other modules, not providers or services.
  2. Step 2: Identify correct placement

    LoggerService should be in providers and exports, but not in imports.
  3. Final Answer:

    LoggerService should not be in the imports array -> Option B
  4. Quick Check:

    Imports array = modules only [OK]
Hint: Imports array only accepts modules, not providers [OK]
Common Mistakes:
  • Putting providers in imports array
  • Confusing controllers with providers
  • Thinking exports are optional for sharing
5. You have two modules, FeatureModule and SharedModule. SharedModule exports UtilityService. You want FeatureModule to use UtilityService and also export it for other modules. How should you configure FeatureModule to achieve this?
hard
A. Import SharedModule and add UtilityService to FeatureModule controllers
B. Only import SharedModule in FeatureModule, no exports needed
C. Declare UtilityService again in FeatureModule providers and exports
D. Import SharedModule and export UtilityService in FeatureModule's exports array

Solution

  1. Step 1: Import SharedModule in FeatureModule

    To use UtilityService, FeatureModule must import SharedModule which exports it.
  2. Step 2: Export UtilityService from FeatureModule

    To share UtilityService further, FeatureModule must export it in its exports array.
  3. Final Answer:

    Import SharedModule and export UtilityService in FeatureModule's exports array -> Option D
  4. Quick Check:

    Import then export to re-share service [OK]
Hint: Import then export shared service to re-share it [OK]
Common Mistakes:
  • Not exporting UtilityService from FeatureModule
  • Re-declaring UtilityService providers unnecessarily
  • Adding services to controllers array
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard