How to Share NestJS Service Globally

Table of Contents

In NestJS, you can make a service available across all modules by declaring it in a global module. Here are the steps to do it:

Create a Service

If you haven’t already, create the service that you want to share using the NestJS CLI. For instance, to create a service called AppService, you would run the following command:

				
					nest g service app

				
			

Create a Global Module

Next, create a module that you will declare as a global module. This could be the same module that the service is a part of, or it could be a separate module. For this example, let’s assume you’re creating a new module called GlobalModule:

				
					nest g module global
				
			

Declare the Module as Global

In the global.module.ts file, you need to add the @Global() decorator from @nestjs/common to declare the module as a global module:

				
					import { Global, Module } from '@nestjs/common';
import { AppService } from './app.service';

@Global()
@Module({
  providers: [AppService],
  exports: [AppService],
})
export class GlobalModule {}

				
			

In this code, the AppService is provided and exported by the GlobalModule, which is marked as global with the @Global() decorator.

Use the Service

Now, the AppService can be imported and used in any module in your NestJS application without needing to import the GlobalModule:

				
					import { Module } from '@nestjs/common';
import { AppService } from './app.service';

@Module({
  providers: [AppService],
})
export class SomeOtherModule {}

				
			

In this code, the AppService is imported and provided in SomeOtherModule, even though GlobalModule is not imported.

Remember that while global modules can be very convenient, they should be used sparingly, as they can make it harder to understand which parts of your application depend on which other parts. It’s usually best to explicitly import the modules that you depend on.

administrator
CEO of CoreCave, I have earned my stripes as a seasoned Senior Full-Stack Web Developer. I'm skilled in a wide range of front-end and back-end languages, responsive frameworks, and databases. My approach to coding is marked by a strict adherence to the best practices, grounding my work in functionality and efficiency. I strive to tackle real-world problems, improve systems, and make a tangible difference in our digital world.