DEV Community

Mukesh Rajbanshi
Mukesh Rajbanshi

Posted on

Redis Caching in NestJS

Nodejs + Redis
Overview

This guide provides a step-by-step process for integrating Redis caching into a NestJS application using Docker and the @keyv/redis package. Redis is an in-memory key-value store that significantly improves application performance by reducing repeated database queries and external API calls. The @keyv/redis package offers a consistent interface and built-in TypeScript support for integrating Redis with minimal configuration.

1. Setting Up Redis Using Docker (Windows CMD)

Prerequisites

  • Ensure Docker Desktop is installed and running on your system.
  • Open Command Prompt (CMD).

Step 1: Pull the Redis Image

docker pull redis
Enter fullscreen mode Exit fullscreen mode

Step 2: Run the Redis Container

docker run -d --name redis-server -p 6379:6379 redis
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • -d: Run container in detached mode (in the background).
  • --name redis-server: Assigns a name to the container.
  • -p 6379:6379: Maps port 6379 of the container to port 6379 on the host machine.

Step 3: Verify the Redis Container is Running

docker ps
Enter fullscreen mode Exit fullscreen mode

Step 4: Access Redis CLI (Optional)

docker exec -it redis-server redis-cli
Enter fullscreen mode Exit fullscreen mode

You can now run Redis commands such as:

set mykey "hello"
get mykey
Enter fullscreen mode Exit fullscreen mode

Step 5: Stop the Redis Container

docker stop redis-server
Enter fullscreen mode Exit fullscreen mode

Step 6: Restart the Redis Container

docker start redis-server
Enter fullscreen mode Exit fullscreen mode

Step 7: View Cache Data in Redis Insight

You can install Redis Insight (GUI tool) to visualize and monitor cached data. It displays keys and their corresponding values stored in Redis.

2. Setting Up Redis In Code

  1. Installing Required Packages in NestJS Run the following commands to install necessary packages:
npm install @nestjs/cache-manager cache-manager
npm install @keyv/redis
Enter fullscreen mode Exit fullscreen mode
  1. Configuring Redis Caching in app.module.ts Update your AppModule to register the Redis cache globally using CacheModule:
import { Module } from '@nestjs/common';
import { createKeyv } from '@keyv/redis';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { CacheInterceptor, CacheModule } from '@nestjs/cache-manager';

@Module({
  imports: [
    CacheModule.registerAsync({
      useFactory: async () => ({
        stores: [createKeyv('redis://localhost:6379')],
        ttl: 60 * 1000,
      }),
      isGlobal: true,
    }),
  ],
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: CacheInterceptor,
    },
  ],
})
export class AppModule {}
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • ttl: Time-to-live for the cache in milliseconds (60,000 ms = 1 minute).
  • isGlobal: true: Makes caching available across the entire application.
  • CacheInterceptor: Automatically caches controller responses based on route and parameters.
  1. How Redis Caching Works in NestJS Once caching is configured globally:
  2. Responses from controller endpoints are cached automatically.
  3. The key is derived from the route and its parameters.
  4. The value is the serialized response.
  5. Redis Insight can be used to verify the stored data.

For example:

KEY: "GET_/users"
VALUE: JSON response of the /users route
Enter fullscreen mode Exit fullscreen mode
  1. Additional Notes
  2. Ensure Redis is running before starting your NestJS application.
  3. For production use, consider securing your Redis server with authentication and SSL.
  4. You can manually manage cache using the CACHE_MANAGER injection token from @nestjs/cache-manager for more granular control.

  5. Enabling Caching for a Single API Endpoint
    While Redis caching can be enabled globally using the CacheInterceptor, you can also enable it selectively for individual routes using the @UseInterceptors decorator in your controller.
    Here’s how to cache a single API endpoint:

import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';

@Controller('users')
export class UserController {

  @Get()
  @UseInterceptors(CacheInterceptor)
  findAll() {
    // Your service logic
  }
}
Enter fullscreen mode Exit fullscreen mode

In the above example:

  • Only the GET /users route will be cached.
  • This approach is helpful when you want to cache specific endpoints instead of globally.

Top comments (0)