0
0
NestJSframework~5 mins

Custom providers in NestJS

Choose your learning style9 modes available
Introduction

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.

When you want to use a class or value that NestJS does not create automatically.
When you want to replace a service with a different version for testing or special cases.
When you want to provide a simple value like a string or number to parts of your app.
When you want to create a service with special setup steps before NestJS uses it.
Syntax
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.

Examples
This provides a simple number value 42 when 'MY_VALUE' is requested.
NestJS
providers: [
  {
    provide: 'MY_VALUE',
    useValue: 42,
  }
]
This tells NestJS to use MyCustomService whenever MyService is requested.
NestJS
providers: [
  {
    provide: MyService,
    useClass: MyCustomService,
  }
]
This uses a factory function to provide a config object.
NestJS
providers: [
  {
    provide: 'CONFIG',
    useFactory: () => ({
      host: 'localhost',
      port: 3000,
    }),
  }
]
This creates an alias 'ALIAS' that points to the same instance as ExistingService.
NestJS
providers: [
  ExistingService,
  {
    provide: 'ALIAS',
    useExisting: ExistingService,
  }
]
Sample Program

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.

NestJS
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();
OutputSuccess
Important Notes

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.

Summary

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.