A cache interceptor helps save time by storing responses so the app doesn't have to redo work for the same request.
0
0
Cache interceptor in NestJS
Introduction
When you want to speed up responses for repeated requests.
When data doesn't change often and can be reused.
To reduce load on your server by avoiding repeated processing.
When you want to improve user experience by delivering faster results.
Syntax
NestJS
import { CacheInterceptor, ExecutionContext, Injectable } from '@nestjs/common'; @Injectable() export class MyCacheInterceptor extends CacheInterceptor { trackBy(context: ExecutionContext): string | undefined { // custom cache key logic return super.trackBy(context); } }
Extend CacheInterceptor to customize caching behavior.
Use trackBy method to define how cache keys are created.
Examples
This example shows using the default cache interceptor as is.
NestJS
import { CacheInterceptor } from '@nestjs/common'; // Use default cache interceptor without changes export class DefaultCacheInterceptor extends CacheInterceptor {}
This example customizes the cache key to use the request URL.
NestJS
import { CacheInterceptor, ExecutionContext, Injectable } from '@nestjs/common'; @Injectable() export class CustomCacheInterceptor extends CacheInterceptor { trackBy(context: ExecutionContext): string | undefined { const request = context.switchToHttp().getRequest(); return request.url; // cache key based on URL } }
Sample Program
This example shows a simple controller using the built-in CacheInterceptor. The first time you call the endpoint, it logs and returns the message. Next calls return cached data without logging.
NestJS
import { Controller, Get, UseInterceptors } from '@nestjs/common'; import { CacheInterceptor, Module } from '@nestjs/common'; import { CacheModule } from '@nestjs/cache-manager'; @Controller('hello') @UseInterceptors(CacheInterceptor) export class HelloController { @Get() getHello() { console.log('Generating response'); return { message: 'Hello, world!' }; } } @Module({ imports: [CacheModule.register()], controllers: [HelloController], providers: [], }) export class AppModule {}
OutputSuccess
Important Notes
Cache interceptor works best with GET requests because they are safe and idempotent.
Remember to enable CacheModule in your app to use caching.
Cached data is stored in memory by default but can be configured to use other stores.
Summary
Cache interceptor stores responses to speed up repeated requests.
Customize cache keys by extending and overriding trackBy.
Use with CacheModule and apply with @UseInterceptors(CacheInterceptor).