A tutorial on adding Redis caching to a NestJS application using the cache-manager library with cache-manager-redis-store. Covers both manual cache operations via the CACHE_MANAGER token and automatic caching via the CacheInterceptor.

Key takeaways

  • Uses four packages: cache-manager, @types/cache-manager, cache-manager-redis-store, @types/cache-manager-redis-store.
  • Configure Redis caching by importing CacheModule.register() with store: redisStore, host, and port in AppModule.
  • Inject CACHE_MANAGER token (typed as Cache from cache-manager) into controllers/services for manual get() and set() operations.
  • Manual set() supports TTL via { ttl: 2000 } option (in milliseconds). Default TTL is 5 seconds.
  • del('key') removes a single cache entry; reset() clears the entire cache.
  • For automatic caching: register CacheInterceptor as APP_INTERCEPTOR in providers, then use @UseInterceptors(CacheInterceptor) on a controller. All @Get() endpoints are auto-cached with the route path as the cache key.
  • Override global TTL per-endpoint with @CacheTTL(seconds) and override the cache key with @CacheKey('custom-key').
  • Auto-caching stores the route path as the Redis key, visible via Redis CLI keys *.

Entities and concepts

Connections to existing knowledge

This is the only source covering NestJS’s built-in caching abstraction layer (CacheModule/CacheInterceptor). It contrasts with the direct ioredis approach described in Using Redis Client in NestJS. The CacheModule approach requires less boilerplate and integrates with NestJS’s decorator system, but offers less control over Redis-specific features (prefixes, connection pooling, underlying driver access). The cache-manager library is store-agnostic — the same API works with in-memory, Redis, or other backends.