How to Use Caching in NestJS: Simple Guide with Examples
In NestJS, you use caching by importing the
CacheModule and applying the @CacheKey() and @CacheTTL() decorators or using the cache manager directly. This allows you to store and retrieve data quickly, improving app performance with minimal setup.Syntax
To use caching in NestJS, first import CacheModule in your module. Then, inject CacheInterceptor globally or locally to enable caching. Use the @CacheKey() and @CacheTTL() decorators to customize cache keys and expiration time.
typescript
import { CacheModule, Module } from '@nestjs/common'; import { APP_INTERCEPTOR } from '@nestjs/core'; import { CacheInterceptor } from '@nestjs/cache-manager'; @Module({ imports: [CacheModule.register({ ttl: 5 })], // ttl in seconds providers: [ { provide: APP_INTERCEPTOR, useClass: CacheInterceptor, }, ], }) export class AppModule {}
Example
This example shows how to cache the result of a controller method using @CacheKey() and @CacheTTL(). The cache stores the response for 10 seconds, so repeated requests within that time return cached data instantly.
typescript
import { Controller, Get, CacheKey, CacheTTL } from '@nestjs/common'; @Controller('time') export class TimeController { @Get() @CacheKey('currentTime') @CacheTTL(10) // cache for 10 seconds getCurrentTime() { return { time: new Date().toISOString() }; } }
Output
{"time":"2024-06-01T12:00:00.000Z"} // same output for 10 seconds on repeated calls
Common Pitfalls
- Not importing
CacheModuleor forgetting to register it causes caching to not work. - Using
CacheInterceptorwithout providing it globally or locally means cache is not applied. - Setting very long TTLs can cause stale data; set TTL based on data freshness needs.
- Cache keys must be unique per method or parameters to avoid collisions.
typescript
/* Wrong: Missing CacheModule import */ @Controller('wrong') export class WrongController { @Get() getData() { return { data: 'no cache' }; } } /* Right: Import CacheModule and use CacheInterceptor */ import { CacheModule, Module } from '@nestjs/common'; import { APP_INTERCEPTOR } from '@nestjs/core'; import { CacheInterceptor } from '@nestjs/cache-manager'; @Module({ imports: [CacheModule.register()], providers: [ { provide: APP_INTERCEPTOR, useClass: CacheInterceptor, }, ], }) export class AppModule {}
Quick Reference
- CacheModule.register({ ttl }): Configure cache with default time-to-live.
- @CacheKey('key'): Set custom cache key for method.
- @CacheTTL(seconds): Set cache expiration time per method.
- CacheInterceptor: Intercepts requests to apply caching automatically.
Key Takeaways
Import and register CacheModule to enable caching in NestJS.
Use CacheInterceptor globally or locally to apply caching to routes.
Customize cache keys and TTL with @CacheKey() and @CacheTTL() decorators.
Avoid stale data by setting appropriate TTL values.
Always test caching behavior to ensure it works as expected.