🦅 NestJS Intermediate

How do you implement caching in NestJS?

Answer

NestJS provides the @nestjs/cache-manager module wrapping the cache-manager library. Import: CacheModule.register({ ttl: 60, max: 100 }). For in-memory caching, inject CACHE_MANAGER: @Inject(CACHE_MANAGER) private cache: Cache. Use: await this.cache.set('key', value); const val = await this.cache.get('key');. The @UseInterceptors(CacheInterceptor) decorator caches entire route responses automatically using the request URL as the key. For distributed caching, use the Redis store: CacheModule.register({ store: redisStore, host: 'localhost' }). Cache invalidation is manual — call cache.del('key') when data changes. Caching is most valuable for expensive, frequently accessed data that changes infrequently.