0
0
NestJSframework~5 mins

CacheModule setup in NestJS

Choose your learning style9 modes available
Introduction

CacheModule helps your app remember data temporarily to make it faster. It avoids doing the same work again and again.

When you want to speed up responses by storing results of slow operations.
When you want to reduce load on a database by caching query results.
When you want to share cached data across different parts of your app.
When you want to set expiration times for data to keep it fresh.
When you want a simple way to add caching without writing complex code.
Syntax
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().

Examples
Cache items expire after 5 seconds.
NestJS
CacheModule.register({ ttl: 5 })
Cache keeps up to 100 items, each expires after 10 seconds.
NestJS
CacheModule.register({ ttl: 10, max: 100 })
Uses default cache settings (ttl: 60 seconds, max: 100 items).
NestJS
CacheModule.register()
Sample Program

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.

NestJS
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 {}
OutputSuccess
Important Notes

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.

Summary

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.