Shared modules help you reuse code easily across different parts of your NestJS app. They keep your code clean and organized.
Shared modules in NestJS
import { Module } from '@nestjs/common'; import { SharedService } from './shared.service'; @Module({ providers: [SharedService], exports: [SharedService], }) export class SharedModule {}
The exports array makes providers available to other modules that import this shared module.
Only providers listed in exports can be used outside the shared module.
import { Module } from '@nestjs/common'; import { LoggerService } from './logger.service'; @Module({ providers: [LoggerService], exports: [LoggerService], }) export class SharedModule {}
import { Module } from '@nestjs/common'; import { SharedModule } from './shared.module'; import { UserService } from './user.service'; @Module({ imports: [SharedModule], providers: [UserService], }) export class UserModule {}
This example shows a SharedModule that exports LoggerService. UserModule imports SharedModule and uses LoggerService inside UserService. When running, it logs a message and returns a user object.
import { Module, Injectable } from '@nestjs/common'; @Injectable() export class LoggerService { log(message: string) { console.log(`Log: ${message}`); } } @Module({ providers: [LoggerService], exports: [LoggerService], }) export class SharedModule {} @Injectable() export class UserService { constructor(private logger: LoggerService) {} createUser(name: string) { this.logger.log(`Creating user: ${name}`); return { name }; } } @Module({ imports: [SharedModule], providers: [UserService], }) export class UserModule {} // Simulate usage async function bootstrap() { const logger = new LoggerService(); const userService = new UserService(logger); const user = userService.createUser('Alice'); console.log(user); } bootstrap();
Always export only what other modules need to use from your shared module.
Import the shared module in any module that needs its exported providers.
Shared modules help avoid duplicate instances of services across your app.
Shared modules let you reuse services and providers across your NestJS app.
Use exports to share providers with other modules.
Import shared modules wherever you need their services.
Practice
Shared Module in NestJS?Solution
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.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.Final Answer:
To share providers and services across multiple modules -> Option CQuick Check:
Shared modules = share providers [OK]
- Confusing shared modules with controllers
- Thinking shared modules define database entities
- Assuming shared modules configure middleware
Solution
Step 1: Recall module decorator properties
Providers are shared by listing them in theexportsarray of the module decorator.Step 2: Understand other arrays
controllersis for controllers,importsis for importing other modules, andbootstrapis not used in modules.Final Answer:
Add the provider to theexportsarray in the module decorator -> Option AQuick Check:
Export providers via exports array [OK]
- Putting providers in controllers array
- Confusing imports with exports
- Using bootstrap array which doesn't exist in modules
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());
}
}
Solution
Step 1: Check provider export and import
SharedModule exports CommonService, and AppModule imports SharedModule, so CommonService is available in AppModule.Step 2: Understand service method call
Calling getMessage() returns the string 'Hello from SharedModule'.Final Answer:
Error: CommonService not found -> Option AQuick Check:
Service must be injected via constructor and registered as provider [OK]
- Forgetting to export the provider
- Not importing the shared module in AppModule
- Assuming service returns undefined
import { Module } from '@nestjs/common';
import { LoggerService } from './logger.service';
@Module({
providers: [LoggerService],
imports: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {}Solution
Step 1: Review module decorator arrays
Theimportsarray is for importing other modules, not providers or services.Step 2: Identify correct placement
LoggerService should be inprovidersandexports, but not inimports.Final Answer:
LoggerService should not be in the imports array -> Option BQuick Check:
Imports array = modules only [OK]
- Putting providers in imports array
- Confusing controllers with providers
- Thinking exports are optional for sharing
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?Solution
Step 1: Import SharedModule in FeatureModule
To use UtilityService, FeatureModule must import SharedModule which exports it.Step 2: Export UtilityService from FeatureModule
To share UtilityService further, FeatureModule must export it in itsexportsarray.Final Answer:
Import SharedModule and export UtilityService in FeatureModule's exports array -> Option DQuick Check:
Import then export to re-share service [OK]
- Not exporting UtilityService from FeatureModule
- Re-declaring UtilityService providers unnecessarily
- Adding services to controllers array
Ready to prove it?
Pass the test and this pattern moves unknown
