0
0
NestJSframework~5 mins

Custom cache keys in NestJS

Choose your learning style9 modes available
Introduction

Custom cache keys help you control how data is stored and retrieved in the cache. This makes your app faster by reusing saved results exactly when you want.

When you want to cache data for specific users separately.
When caching results of a function that depends on multiple inputs.
When you want to avoid cache conflicts by naming keys clearly.
When you want to customize cache expiration per key.
When you want to debug or monitor cache usage with meaningful keys.
Syntax
NestJS
import { CacheKey, CacheTTL, CacheInterceptor, Controller, Get, UseInterceptors } from '@nestjs/common';

@Controller('items')
@UseInterceptors(CacheInterceptor)
export class ItemsController {
  @Get()
  @CacheKey('custom_key_name')
  @CacheTTL(60) // seconds
  findAll() {
    return ['item1', 'item2'];
  }
}

@CacheKey() sets a custom name for the cache entry.

@CacheTTL() sets how long the cache lasts in seconds.

Examples
This caches the user profile under the key 'user_123_profile'.
NestJS
@CacheKey('user_123_profile')
findUserProfile() {
  return { name: 'Alice', age: 30 };
}
You can use a function to create dynamic cache keys based on input.
NestJS
@CacheKey((pageNumber: number) => `items_page_${pageNumber}`)
findItems(pageNumber: number) {
  return getItems(pageNumber);
}
This caches all products for 2 minutes with a custom key.
NestJS
@CacheKey('all_products')
@CacheTTL(120)
getAllProducts() {
  return fetchProducts();
}
Sample Program

This controller caches the list of books under the key 'books_list' for 30 seconds. The console log shows when the data is fetched fresh.

NestJS
import { CacheKey, CacheTTL, CacheInterceptor, Controller, Get, UseInterceptors } from '@nestjs/common';

@Controller('books')
@UseInterceptors(CacheInterceptor)
export class BooksController {
  private books = ['Book A', 'Book B', 'Book C'];

  @Get()
  @CacheKey('books_list')
  @CacheTTL(30)
  getBooks() {
    console.log('Fetching books from source');
    return this.books;
  }
}
OutputSuccess
Important Notes

Custom cache keys help avoid overwriting cached data accidentally.

Use meaningful keys to make debugging easier.

Remember to set cache TTL to control how fresh your data stays.

Summary

Custom cache keys let you name cached data clearly.

They help store and retrieve data exactly as you want.

Use decorators like @CacheKey() and @CacheTTL() in NestJS.