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
typescript
type Operator = "=" | "!=" | ">" | "<" | ">=" | "<=" | "LIKE"; type Row = Record<string, unknown>;
A type-safe SQL query builder in TypeScript
builder pattern
generics
method chaining
Intermediate
8 steps
typescript
import { Directive, ElementRef, HostListener, Input, OnDestroy, OnInit } from '@angular/core'; @Directive({ selector: '[appTrapFocus]',
Building a focus-trap directive in Angular
accessibility
focus-management
dom
Intermediate
9 steps
java
package com.example.payments.config; import com.stripe.StripeClient; import org.springframework.beans.factory.annotation.Value;
Swapping payment gateways by profile in Spring
dependency-injection
profiles
configuration
Intermediate
6 steps
rust
use std::env; use std::time::Duration; #[derive(Debug, Clone)]
Loading typed config from environment variables in Rust
configuration
error-handling
generics
Intermediate
7 steps
typescript
type AsyncFn<A extends unknown[], R> = (...args: A) => Promise<R>; interface MemoizeOptions<A extends unknown[]> { keyFn?: (...args: A) => string;
Memoizing async functions with TTL in TypeScript
memoization
generics
promises
Advanced
8 steps
typescript
import { Injectable, Scope, Inject } from '@nestjs/common'; import { REQUEST } from '@nestjs/core'; import { Request } from 'express';
Request-scoped context service in NestJS
dependency-injection
request-scope
immutability
Intermediate
8 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.