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.
Previous
What is the Reflector in NestJS and how is it used?
Next
What is event-driven architecture in NestJS using the EventEmitter?
More NestJS Questions
View all →- Intermediate How does NestJS dependency injection scoping work?
- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate How do you implement role-based access control (RBAC) in NestJS?
- Intermediate What is the Reflector in NestJS and how is it used?