Discover how to stop repeating imports and make your NestJS services truly global!
Why Global modules in NestJS? - Purpose & Use Cases
Imagine you have many parts of your NestJS app that need the same service, like a logging tool. You have to import and provide it in every module manually.
This manual way is tiring and easy to forget. If you miss importing the service somewhere, your app breaks. It also clutters your code with repeated imports.
Global modules let you register a module once, and NestJS shares its services everywhere automatically. No need to import it repeatedly.
imports: [LoggerModule], // repeated in every module@Global()
@Module({
providers: [LoggerService],
exports: [LoggerService],
})
export class LoggerModule {} // imported once globallyGlobal modules make your app cleaner and ensure shared services are always available without extra imports.
A logging module used by controllers, services, and guards across your whole NestJS app without importing it in each module.
Manually importing shared modules is repetitive and error-prone.
Global modules provide shared services app-wide automatically.
This leads to cleaner, easier-to-maintain code.