CacheModule helps your app remember data temporarily to make it faster. It avoids doing the same work again and again.
CacheModule setup in NestJS
import { CacheModule } from '@nestjs/common'; @Module({ imports: [ CacheModule.register({ ttl: 60, // seconds to keep cache max: 100, // max items in cache }), ], }) export class AppModule {}
ttl means how long the cache stays before it clears automatically.
You can customize cache settings globally by passing options to register().
CacheModule.register({ ttl: 5 })CacheModule.register({ ttl: 10, max: 100 })CacheModule.register()
This example sets up caching for the /count route. The first time you call it, it increases the counter. For 10 seconds, repeated calls return the cached count without increasing it.
import { Module, Controller, Get, CacheInterceptor, UseInterceptors } from '@nestjs/common'; import { CacheModule } from '@nestjs/common'; @Controller() @UseInterceptors(CacheInterceptor) export class AppController { private counter = 0; @Get('count') getCount() { this.counter++; return { count: this.counter }; } } @Module({ imports: [CacheModule.register({ ttl: 10 })], controllers: [AppController], }) export class AppModule {}
CacheModule uses in-memory cache by default, which is good for simple apps or development.
For production, consider using external stores like Redis by using CacheModule.registerAsync() with custom store.
Remember to use @UseInterceptors(CacheInterceptor) on controllers or routes to enable caching behavior.
CacheModule helps speed up your app by storing data temporarily.
You set it up by importing and registering it with options like ttl.
Use cache interceptors to apply caching to routes easily.