The FactoryProvider pattern in NestJS is a provider definition that uses a factory function to create a provider instance, rather than instantiating a class directly. It is defined via the FactoryProvider interface from @nestjs/common.

Usage for Redis

In the context of Redis integration, FactoryProvider creates a singleton ioredis client:

export const redisClientFactory: FactoryProvider<Redis> = {
  provide: 'RedisClient',
  useFactory: () => {
    const redisInstance = new Redis({
      host: process.env.REDIS_HOST,
      port: +process.env.REDIS_PORT,
    });
    redisInstance.on('error', e => {
      throw new Error(`Redis connection failed: ${e}`);
    });
    return redisInstance;
  },
  inject: [],
};

The injection token 'RedisClient' is then used by the Redis Repository Pattern to receive the singleton instance.

Why FactoryProvider for Redis

  • Allows reading environment variables at startup (not available in decorator-based injection)
  • Enables custom error handling during connection
  • Returns the raw ioredis instance which is not a NestJS class and cannot use @Injectable()