NestJS - Redis

Nikos Oikonomou
2 min readJan 27, 2024

In this section, we’ll introduce a new module that uses ioredis and enables our NestJS application to connect to Redis.

This section is part of a larger guide. You can follow it from the beginning or just complete the only prerequisite step (getting started).

At this point, you should have a fully operational NestJS project to follow the upcoming steps.

Our new Redis module will provide two ways to connect and communicate with Redis. The first one is a standard ioredis connection and the second one is by configuring the standard NestJS Redis transporter (uses ioredis internally).

Let’s start by installing the needed packages:

npm i @nestjs/microservices ioredis @nestjs/config

We’ll first introduce a config instance that provides all the needed ioredis settings.

By default, it will connect to redis://@localhost:6379/0 and by providing the appropriate env variables (REDIS_HOST, REDIS_PORT, REDIS_USERNAME, REDIS_PASSWORD, REDIS_DB) the application can connect to any Redis server.

We’ll provide a service that will extend ioredis and will act as a “raw” Redis client for packages that can’t work with Redis Transporter (e.g. connect-redis).

It basically just setups the connection, logs incoming events and provides ioredis interface methods to be used by other services in the application.

Now that we have the ioredis client ready, we can also set up the NestJS Transporter for our “high” level redis access:

Don’t forget to import your new redis module at your app.module.ts :

@Module({
imports: [RedisModule]
})
export class AppModule {}

Now your application connects to Redis and your services can use it for Redis operations (e.g. caching values).

Hint: test suites that use this redis module should close the connection by calling redisService.onModuleDestroy (or app.close() that destroys all modules). Example:

afterAll(async () => {
service.onModuleDestroy();
});
orafterAll(async () => {
await app.close();
});

--

--