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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A Symbol injection token gives non-class dependencies a collision-proof identity in the DI container.
- 2useFactory can be async, letting a provider await connection setup before it becomes available.
- 3Exporting a provider lets other modules consume the same shared, already-connected instance.
Related explainers
typescript
import { NestFactory } from '@nestjs/core'; import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'; import { ValidationPipe } from '@nestjs/common'; import { ApiProperty } from '@nestjs/swagger';
Wiring validation and Swagger docs in NestJS
validation
openapi
decorators
Intermediate
8 steps
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
java
public interface GitHubClient { @GetExchange("/users/{username}") GitHubUser getUser(@PathVariable String username);
Declarative HTTP clients in Spring
http-client
declarative-api
proxy
Intermediate
8 steps
typescript
import { Component, Input } from '@angular/core'; interface Order { id: string;
How Angular ICU plurals localize an order summary
i18n
pluralization
standalone-component
Intermediate
8 steps
php
<?php namespace App\Providers;
Subdomain multi-tenancy routing in Laravel
multi-tenancy
service-container
route-binding
Advanced
7 steps
typescript
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable, catchError, concatMap, finalize } from 'rxjs'; import { DataSource, QueryRunner } from 'typeorm';
Wrapping requests in a transaction with NestJS
interceptors
transactions
rxjs
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/provide-a-redis-client-with-a-nestjs-factory-explained-typescript-7f88/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.