A cache interceptor helps save time by storing responses so the app doesn't have to redo work for the same request.
Cache interceptor in 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.
import { CacheInterceptor } from '@nestjs/common'; // Use default cache interceptor without changes export class DefaultCacheInterceptor extends CacheInterceptor {}
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 } }
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.
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 {}
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.
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).
Practice
CacheInterceptor in NestJS?Solution
Step 1: Understand the role of CacheInterceptor
The CacheInterceptor caches HTTP responses to avoid recomputing them on repeated requests.Step 2: Compare with other options
Logging, authentication, and formatting are handled by other interceptors or middleware, not CacheInterceptor.Final Answer:
To store responses and speed up repeated requests -> Option BQuick Check:
CacheInterceptor caches responses = C [OK]
- Confusing CacheInterceptor with logging interceptors
- Thinking it handles security tasks
- Assuming it formats data
Solution
Step 1: Recall how to apply interceptors in NestJS
Interceptors are applied using the@UseInterceptors()decorator above methods or controllers.Step 2: Check each option
Only @UseInterceptors(CacheInterceptor) above the method uses the correct decorator syntax. Options B, C, and D are invalid or do not exist in NestJS.Final Answer:
@UseInterceptors(CacheInterceptor) above the method -> Option CQuick Check:
UseInterceptors decorator = A [OK]
- Using non-existent @Cacheable decorator
- Trying to inject interceptor in constructor
- Passing interceptor as method parameter
/hello?
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';
@Controller()
export class HelloController {
private count = 0;
@UseInterceptors(CacheInterceptor)
@Get('hello')
getHello() {
this.count++;
return `Hello count: ${this.count}`;
}
}Solution
Step 1: Understand CacheInterceptor behavior
CacheInterceptor caches the response of the first request and returns it for subsequent requests without calling the method again.Step 2: Analyze the count variable increment
On the first request, count increments to 1 and returns "Hello count: 1". On the second request, the cached response is returned, so count does not increment again.Final Answer:
"Hello count: 1" on first and second request -> Option DQuick Check:
Cache returns cached response = B [OK]
- Assuming count increments on every request
- Thinking private variables cause errors here
- Ignoring caching effect on method execution
import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';
@Controller()
export class TestController {
@UseInterceptors(CacheInterceptor())
@Get('test')
test() {
return 'Test response';
}
}Solution
Step 1: Check how CacheInterceptor is applied
CacheInterceptor is a class, not a function, so it should be passed without parentheses to@UseInterceptors().Step 2: Verify other options
CacheModule import is required but not shown here (not an error in this snippet). Method does not need to be async. CacheInterceptor can be applied per method.Final Answer:
CacheInterceptor should not be called as a function -> Option AQuick Check:
Use class name without () = A [OK]
- Calling CacheInterceptor with parentheses
- Assuming method must be async
- Thinking CacheModule import error here
Solution
Step 1: Understand how to customize cache keys
CacheInterceptor allows customization by extending it and overriding thetrackBymethod to define how keys are generated.Step 2: Evaluate other options
Passing a string to@UseInterceptors()is invalid. Setting keys in constructor or using@CacheKeydecorator does not exist in NestJS.Final Answer:
Extend CacheInterceptor and override thetrackBymethod to return a custom key -> Option AQuick Check:
Override trackBy method = D [OK]
- Trying to pass key directly to decorator
- Using non-existent @CacheKey decorator
- Setting keys in constructor instead of method
Ready to prove it?
Pass the test and this pattern moves unknown
