typescript 35 lines · 6 steps

Provide a Redis client with a NestJS factory

A NestJS module wires a connected Redis client into the DI container using an async factory provider.

Explained by highlit
1import { Module } from '@nestjs/common';
2import { ConfigModule, ConfigService } from '@nestjs/config';
3import { createClient, RedisClientType } from 'redis';
4 
5export const REDIS_CLIENT = Symbol('REDIS_CLIENT');
6 
7@Module({
8 imports: [ConfigModule],
9 providers: [
10 {
11 provide: REDIS_CLIENT,
12 inject: [ConfigService],
13 useFactory: async (config: ConfigService): Promise<RedisClientType> => {
14 const client: RedisClientType = createClient({
15 url: config.getOrThrow<string>('REDIS_URL'),
16 socket: {
17 connectTimeout: 5_000,
18 reconnectStrategy: (retries) => Math.min(retries * 100, 3_000),
19 },
20 });
21 
22 client.on('error', (err) => {
23 console.error('Redis client error', err);
24 });
25 
26 await client.connect();
27 await client.ping();
28 
29 return client;
30 },
31 },
32 ],
33 exports: [REDIS_CLIENT],
34})
35export class RedisModule {}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A Symbol injection token gives non-class dependencies a collision-proof identity in the DI container.
  2. 2useFactory can be async, letting a provider await connection setup before it becomes available.
  3. 3Exporting a provider lets other modules consume the same shared, already-connected instance.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Provide a Redis client with a NestJS factory — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code