TTL configuration helps you set how long data should live before it expires automatically. This keeps your app's data fresh and avoids clutter.
0
0
TTL configuration in NestJS
Introduction
You want to cache API responses for a short time to improve speed.
You need to automatically remove old session data after some minutes.
You want to limit how long temporary tokens stay valid.
You want to clear outdated notifications after a set time.
You want to manage memory by deleting unused data automatically.
Syntax
NestJS
CacheModule.register({
ttl: number_in_seconds
})ttl means 'time to live' in seconds.
After this time, cached data is removed automatically.
Examples
Cache data expires after 60 seconds.
NestJS
CacheModule.register({ ttl: 60 })Cache data never expires automatically.
NestJS
CacheModule.register({ ttl: 0 })Cache data expires after 5 minutes (300 seconds).
NestJS
CacheModule.register({ ttl: 300 })Sample Program
This example sets up a cache with a default TTL of 10 seconds. The setCache route stores a value with a 5-second TTL. The getCache route retrieves it. After 5 seconds, the cached value expires and returns a message.
NestJS
import { CacheModule, Module, Controller, Get, Inject, CACHE_MANAGER } from '@nestjs/common'; import { Cache } from 'cache-manager'; @Controller() export class AppController { constructor(@Inject(CACHE_MANAGER) private cacheManager: Cache) {} @Get('set') async setCache() { await this.cacheManager.set('key', 'Hello TTL', { ttl: 5 }); return 'Value cached with 5 seconds TTL'; } @Get('get') async getCache() { const value = await this.cacheManager.get('key'); return value ?? 'Cache expired or not set'; } } @Module({ imports: [CacheModule.register({ ttl: 10 })], controllers: [AppController], }) export class AppModule {}
OutputSuccess
Important Notes
You can set TTL globally in CacheModule.register() or per item when setting cache.
TTL is in seconds, so 60 means one minute.
Setting TTL to 0 means the cache never expires automatically.
Summary
TTL controls how long cached data stays before automatic removal.
Use TTL to keep data fresh and save memory.
You can set TTL globally or per cached item.