Custom providers let you tell NestJS how to create or find a value or service. This helps you control what your app uses in different places.
Custom providers in NestJS
providers: [
{
provide: TOKEN_OR_CLASS,
useClass: ClassToUse,
},
{
provide: TOKEN_OR_CLASS,
useValue: someValue,
},
{
provide: TOKEN_OR_CLASS,
useFactory: () => {
return new SomeClass();
},
},
{
provide: TOKEN_OR_CLASS,
useExisting: ExistingProvider,
}
]provide is the token or class name NestJS uses to find this provider.
You can use useClass, useValue, useFactory, or useExisting to tell NestJS how to get the value.
providers: [
{
provide: 'MY_VALUE',
useValue: 42,
}
]MyCustomService whenever MyService is requested.providers: [
{
provide: MyService,
useClass: MyCustomService,
}
]providers: [
{
provide: 'CONFIG',
useFactory: () => ({
host: 'localhost',
port: 3000,
}),
}
]ExistingService.providers: [
ExistingService,
{
provide: 'ALIAS',
useExisting: ExistingService,
}
]This example shows how to create a custom provider named 'Logger' that uses CustomLoggerService instead of the default LoggerService. The AppService asks for 'Logger' and gets the custom version. When run() is called, it logs with the custom prefix.
import { Injectable, Module, Inject } from '@nestjs/common'; @Injectable() class LoggerService { log(message: string) { console.log('LOG:', message); } } @Injectable() class CustomLoggerService { log(message: string) { console.log('CUSTOM LOG:', message); } } @Injectable() class AppService { constructor(@Inject('Logger') private logger: LoggerService) {} run() { this.logger.log('App is running'); } } @Module({ providers: [ AppService, { provide: 'Logger', useClass: CustomLoggerService, }, ], }) export class AppModule {} // Simulate NestJS bootstrap and usage async function bootstrap() { // Manually create instances to simulate NestJS DI const logger = new CustomLoggerService(); const appService = new AppService(logger); appService.run(); } bootstrap();
Custom providers let you swap implementations without changing the code that uses them.
Use useValue for simple constants, useClass for classes, useFactory for dynamic creation, and useExisting to alias providers.
Always provide a unique token or class in provide to avoid conflicts.
Custom providers control how NestJS creates or finds a service or value.
You can provide classes, values, factories, or aliases using different keys.
This helps make your app flexible and easy to test.