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

typescript
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';
import localeDe from '@angular/common/locales/de';

Locale-aware bootstrapping in Angular

i18n localization dependency-injection
Intermediate 8 steps
typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import * as Joi from 'joi';
 

Validating env config at boot in NestJS

configuration schema-validation environment-variables
Intermediate 8 steps
java
@Component
@Converter
public class EncryptedStringConverter implements AttributeConverter<String, String> {
 

Transparent column encryption in Spring & JPA

encryption aes-gcm jpa-converter
Advanced 10 steps
typescript
import { Inject, Injectable, Logger } from '@nestjs/common';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { InjectRepository } from '@nestjs/typeorm';

A cache-aside country lookup in NestJS

cache-aside dependency-injection batch-lookup
Intermediate 8 steps
java
package com.acme.billing.config;
 
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;

Feature-flagged beans with Spring @ConditionalOnProperty

feature-flags conditional-beans strategy-pattern
Intermediate 5 steps
typescript
import { Injectable, effect, signal, computed } from '@angular/core';
 
interface Preferences {
  theme: 'light' | 'dark';

A signal-based preferences store in Angular

signals state-management persistence
Intermediate 7 steps

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