0
0
NestJSframework~5 mins

Shared modules in NestJS

Choose your learning style9 modes available
Introduction

Shared modules help you reuse code easily across different parts of your NestJS app. They keep your code clean and organized.

When you have services or components used in many places in your app.
When you want to avoid repeating the same providers in multiple modules.
When you want to share utility functions or constants across modules.
When you want to keep your app modular and easy to maintain.
Syntax
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.

Examples
This shared module provides and exports a LoggerService to be used in other modules.
NestJS
import { Module } from '@nestjs/common';
import { LoggerService } from './logger.service';

@Module({
  providers: [LoggerService],
  exports: [LoggerService],
})
export class SharedModule {}
UserModule imports SharedModule to use its exported services like LoggerService.
NestJS
import { Module } from '@nestjs/common';
import { SharedModule } from './shared.module';
import { UserService } from './user.service';

@Module({
  imports: [SharedModule],
  providers: [UserService],
})
export class UserModule {}
Sample Program

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.

NestJS
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();
OutputSuccess
Important Notes

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.

Summary

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.