โ† Blog

NestJS Custom Providers: useValue, useClass, and useFactory

Sometimes a dependency is not a normal service class. You may need to inject configuration, reuse an existing library instance, swap an implementation, or build a value from other providers. Custom providers let you tell NestJS exactly what should be supplied for an injection token.

1. useValue: provide an existing value

Use useValue for constants, configuration objects, external instances, or test mocks.

{
  provide: 'APP_NAME',
  useValue: 'Taskify',
}

Inject the token with @Inject():

@Injectable()
export class AppService {
  constructor(@Inject('APP_NAME') private name: string) {}
}

2. useClass: choose an implementation

Use useClass when a token should resolve to a particular class. For example, an application can depend on a logger contract while the module selects the implementation:

{
  provide: LoggerService,
  useClass: ConsoleLoggerService,
}

Consumers that request the LoggerService token receive the configured class. This is useful for switching implementations or replacing real services in tests.

3. useFactory: build a dependency dynamically

A factory creates the value when Nest resolves the provider. It can also receive other providers through the inject array:

{
  provide: 'GREETING',
  useFactory: (config: ConfigService) => {
    return config.get('GREETING') ?? 'Hello';
  },
  inject: [ConfigService],
}

Nest resolves ConfigService and passes it as the factoryโ€™s first argument. The order of entries in inject matches the factory parameters.

Tokens and registration

A custom provider is registered in a moduleโ€™s providers array. Its provide property is the token consumers use to request it. Tokens can be classes, strings, or symbols. For larger applications, keep shared tokens in a dedicated file to avoid spelling mistakes and accidental collisions.

Choose the simplest option: useValue for a ready-made value, useClass for an implementation, and useFactory when creation needs logic or other dependencies.

Reference: NestJS Custom Providers