typescript
48 lines · 8 steps
Building a dynamic Redis module in NestJS
A configurable NestJS module that provides a shared Redis client through both static and async factory registration.
Explained by
highlit
1import { DynamicModule, Module, Provider } from '@nestjs/common';
2import Redis, { RedisOptions } from 'ioredis';
3
4export const REDIS_CLIENT = Symbol('REDIS_CLIENT');
5export const REDIS_OPTIONS = Symbol('REDIS_OPTIONS');
6
7export interface RedisModuleAsyncOptions {
8 useFactory: (...args: any[]) => Promise<RedisOptions> | RedisOptions;
9 inject?: any[];
10}
11
12@Module({})
13export class RedisModule {
14 static forRoot(options: RedisOptions): DynamicModule {
15 const clientProvider: Provider = {
16 provide: REDIS_CLIENT,
17 useValue: new Redis(options),
18 };
19
20 return {
21 module: RedisModule,
22 global: true,
23 providers: [clientProvider],
24 exports: [clientProvider],
25 };
26 }
27
28 static forRootAsync(options: RedisModuleAsyncOptions): DynamicModule {
29 const optionsProvider: Provider = {
30 provide: REDIS_OPTIONS,
31 useFactory: options.useFactory,
32 inject: options.inject ?? [],
33 };
34
35 const clientProvider: Provider = {
36 provide: REDIS_CLIENT,
37 useFactory: (opts: RedisOptions) => new Redis(opts),
38 inject: [REDIS_OPTIONS],
39 };
40
41 return {
42 module: RedisModule,
43 global: true,
44 providers: [optionsProvider, clientProvider],
45 exports: [clientProvider],
46 };
47 }
48}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A DynamicModule lets a module return its own provider configuration at runtime instead of declaring it statically.
- 2Symbol tokens give injectable providers stable, collision-proof identifiers when there's no class to inject.
- 3Offering both forRoot and forRootAsync lets callers pass config directly or resolve it lazily via a factory and injected dependencies.
Related explainers
java
public record AppConfig( String host, int port, String databaseUrl,
Loading typed config from env vars in Java
records
configuration
environment-variables
Intermediate
6 steps
typescript
export function isValidCardNumber(input: string): boolean { const digits = input.replace(/[\s-]/g, ""); if (!/^\d{12,19}$/.test(digits)) {
Validating card numbers with the Luhn check
luhn-algorithm
checksum
input-validation
Intermediate
7 steps
typescript
interface UserAgentInfo { browser: { name: string; version: string }; os: { name: string; version: string }; device: 'mobile' | 'tablet' | 'desktop';
Parsing a user-agent string with ordered rules
regex
parsing
pattern-matching
Intermediate
9 steps
typescript
import { Injectable, inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, timer, throwError } from 'rxjs'; import { switchMap, takeWhile, filter, take, catchError } from 'rxjs/operators';
Polling a job until it finishes in Angular
rxjs
polling
observables
Intermediate
7 steps
php
<?php namespace App\Http\Controllers;
Handling Stripe webhooks in Laravel
webhooks
signature-verification
dependency-injection
Intermediate
7 steps
typescript
type Flatten = Record<string, unknown>; function isPlainObject(value: unknown): value is Record<string, unknown> { return (
Flattening nested objects into dotted keys
recursion
reduce
type-guards
Intermediate
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/building-a-dynamic-redis-module-in-nestjs-explained-typescript-4055/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.