🦅 NestJS Advanced

What is custom provider syntax in NestJS (useClass, useValue, useFactory)?

Answer

NestJS supports advanced provider definitions beyond the simple class syntax. useClass: swap implementation based on environment: { provide: ConfigService, useClass: process.env.NODE_ENV === 'test' ? MockConfigService : ConfigService }. useValue: provide a static value or mock: { provide: 'APP_VERSION', useValue: '1.0.0' }. Inject with @Inject('APP_VERSION') version: string. useFactory: create providers with async initialization or dependencies: { provide: 'DB_CONNECTION', useFactory: async (config: ConfigService) => { return await createConnection(config.get('DB_URL')); }, inject: [ConfigService] }. useExisting: alias one provider to another. These patterns enable sophisticated DI configurations for testing, feature flags, and platform-agnostic code.