0
0
NestJSframework~5 mins

Global modules in NestJS

Choose your learning style9 modes available
Introduction

Global modules let you share services or providers across your whole NestJS app without importing them everywhere.

You have a service used in many parts of your app, like logging or configuration.
You want to avoid repeating imports of the same module in multiple feature modules.
You want to keep your app organized by centralizing common utilities.
You need a singleton service that should be the same everywhere.
You want to simplify module dependencies for easier maintenance.
Syntax
NestJS
import { Module, Global } from '@nestjs/common';

@Global()
@Module({
  providers: [MyService],
  exports: [MyService],
})
export class MyGlobalModule {}

The @Global() decorator marks the module as global.

You must export the providers you want to share globally.

Examples
This example creates a global ConfigModule that shares ConfigService everywhere.
NestJS
import { Module, Global } from '@nestjs/common';

@Global()
@Module({
  providers: [ConfigService],
  exports: [ConfigService],
})
export class ConfigModule {}
This example shows a global LoggerModule for logging across the app.
NestJS
import { Module, Global } from '@nestjs/common';

@Global()
@Module({
  providers: [LoggerService],
  exports: [LoggerService],
})
export class LoggerModule {}
Sample Program

This example shows a global GreetingModule that provides GreetingService everywhere. The WelcomeService uses GreetingService without importing GreetingModule again. The console prints a greeting message.

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

@Injectable()
export class GreetingService {
  sayHello(name: string): string {
    return `Hello, ${name}!`;
  }
}

@Global()
@Module({
  providers: [GreetingService],
  exports: [GreetingService],
})
export class GreetingModule {}

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

// Usage in any other module without importing GreetingModule again
import { Injectable } from '@nestjs/common';

@Injectable()
export class WelcomeService {
  constructor(private greetingService: GreetingService) {}

  welcomeUser(user: string): string {
    return this.greetingService.sayHello(user);
  }
}

// Simulate usage
const welcomeService = new WelcomeService(new GreetingService());
console.log(welcomeService.welcomeUser('Alice'));
OutputSuccess
Important Notes

Global modules are registered once and shared app-wide.

Use global modules sparingly to avoid hidden dependencies.

You still need to import the global module once in your root module.

Summary

Global modules share providers across the whole app without repeated imports.

Mark a module with @Global() and export its providers.

Use global modules for common services like config or logging.