Progressive Full Stack Application Development with Live Projects

Nest JS

Make a Service Global in NestJS

Logging is an important aspect of the application development. Backend engineers depend on logging during the development.In the last lesson we covered how to implement a custom logging feature for our Nest JS application. In the process we created a Service, but now we want the service to be available globally.

Lesson Goal

To use the LoggerService application-wide in a NestJS application, you need to make it globally available by providing it in the root module (usually AppModule). This way, you can inject and use it in any part of your application without having to import it manually in each individual module.

1. Decorate the Logger Service as Global

We can make the LoggerService globally available by using the @Global() decorator on your LoggerModule. The @Global() decorator ensures that the module is globally available.

				
					import { Module, Global } from '@nestjs/common';
import { LoggerService } from './logger.service';

@Global()
@Module({
  providers: [LoggerService],
  exports: [LoggerService], // Export the LoggerService to make it available app-wide
})
export class LoggerModule {}

				
			

2. Update the Root Module

Let us import our logger module in the app.module.ts file or the root module of Nest App. By importing LoggerModule, the LoggerService will be globally available to the entire application.

				
					import { Module } from '@nestjs/common';
import { LoggerModule } from './logger/logger.module'; // Import LoggerModule
import { ExampleController } from './example/example.controller';

@Module({
  imports: [LoggerModule], // Import the LoggerModule
  controllers: [ExampleController],
  providers: [],
})
export class AppModule {}
				
			

Now that the LoggerService is globally available, you can inject it into any other services or controllers in your application without needing to import the LoggerModule again.

By marking the LoggerModule as @Global() and exporting the LoggerService, you make the logger globally accessible throughout the entire application. You no longer need to import the LoggerModule into every individual module. This is an efficient way to use the LoggerService application-wide in NestJS.