DEV Community

Cover image for Level Up Your NestJS App with RedisX
Suren Krmoian
Suren Krmoian

Posted on

Level Up Your NestJS App with RedisX

Level Up Your NestJS App with RedisX

Diving into Redis with NestJS? Many of us start with ioredis for basic operations. But as your app grows, things get hairy. Caching, distributed locks, observability—suddenly, the simple setup isn't cutting it. This is where NestJS RedisX steps in. It's a toolkit that wraps up all those extra Redis features you need, neatly integrated into the NestJS framework.

What's Wrong with Just ioredis?

Honestly, nothing. If you're okay with juggling Redis connections, manual caching, and everything else by yourself. But let's face it, as projects scale, this manual handling turns into a maintenance nightmare. RedisX takes away that pain by offering a streamlined API that's baked right into NestJS. Less hassle, more productivity.

Getting Started with RedisX

Step 1: Install the Essentials

First things first, let's get RedisX into your project. Focus on the core package and the plugins you need. We'll deal with caching and locks here:

npm install @nestjs-redisx/core @nestjs-redisx/cache @nestjs-redisx/locks
Enter fullscreen mode Exit fullscreen mode

Step 2: Set Up the Redis Module

Time to swap out your old ioredis setup. Configure the RedisModule in your AppModule like this:

import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { RedisModule } from '@nestjs-redisx/core';
import { CachePlugin } from '@nestjs-redisx/cache';
import { LocksPlugin } from '@nestjs-redisx/locks';

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    RedisModule.forRootAsync({
      imports: [ConfigModule],
      inject: [ConfigService],
      plugins: [
        CachePlugin.registerAsync({
          inject: [ConfigService],
          useFactory: (config: ConfigService) => ({
            defaultTtl: config.get('CACHE_TTL', 300),
          }),
        }),
        new LocksPlugin({ retryAttempts: 3 }),
      ],
      useFactory: (config: ConfigService) => ({
        clients: {
          type: 'single',
          host: config.get('REDIS_HOST', 'localhost'),
          port: config.get('REDIS_PORT', 6379),
        },
      }),
    }),
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Step 3: Transform Your Service Logic

Change your cache logic from ioredis commands to RedisX decorators. Here's a quick switch:

Before (ioredis):

async getUser(id: string): Promise<User> {
  const cached = await this.redis.get(`user:${id}`);
  if (cached) return JSON.parse(cached);
  const user = await this.userRepository.findById(id);
  await this.redis.setex(`user:${id}`, 3600, JSON.stringify(user));
  return user;
}
Enter fullscreen mode Exit fullscreen mode

After (RedisX):

import { Injectable } from '@nestjs/common';
import { Cached } from '@nestjs-redisx/cache';

@Injectable()
export class UserService {
  @Cached({ key: 'user:{0}', ttl: 3600 })
  async getUser(id: string): Promise<User> {
    return this.userRepository.findById(id);
  }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Handling Distributed Locks

Ditch the manual lock logic. Use RedisX's @WithLock decorator for a cleaner and safer approach.

Before (ioredis):

const lock = await this.redis.set(lockKey, uuid(), 'EX', 30, 'NX');
if (!lock) throw new Error('Lock acquisition failed');
try { await this.doWork(); }
finally { await this.redis.del(lockKey); }
Enter fullscreen mode Exit fullscreen mode

After (RedisX):

import { WithLock } from '@nestjs-redisx/locks';

@WithLock({ key: 'resource:{0}', ttl: 5000 })
async secureResourceAccess(resourceId: string) {
  await this.doWork(resourceId);
}
Enter fullscreen mode Exit fullscreen mode

Why Make the Switch?

RedisX isn't just a nice-to-have. It's packed with advanced features like L1+L2 caching, distributed locks, and more—all under one roof. Your codebase becomes cleaner, less error-prone, and ready for scale. Dive into the official docs for more.

Ready to take your NestJS app to the next level? RedisX is your friend. Give it a go.

Top comments (1)

Collapse
 
vaviloff profile image
Vaviloff

Thanks, didn't know about RedisX until today, great writeup!