What if your server could remember answers and save time without you lifting a finger?
Why Cache interceptor in NestJS? - Purpose & Use Cases
Imagine your server has to process the same request multiple times, like fetching user data every time someone clicks a button.
Each time, it repeats the same heavy work, slowing down responses and wasting resources.
Manually handling caching means writing extra code everywhere.
This is error-prone, easy to forget, and hard to maintain.
It also clutters your business logic and can cause inconsistent data if not done carefully.
The Cache interceptor in NestJS automatically stores and returns cached responses for repeated requests.
This keeps your code clean and speeds up responses without extra manual work.
if (cache.has(key)) { return cache.get(key); } const result = await fetchData(); cache.set(key, result); return result;
@UseInterceptors(CacheInterceptor)
async getData() {
return await fetchData();
}It enables fast, efficient responses by reusing previous results automatically, improving user experience and saving server power.
Think of an online store showing product details. Instead of fetching the same product info from the database every time, the Cache interceptor quickly serves the stored data.
Manual caching is repetitive and error-prone.
Cache interceptor automates caching cleanly and reliably.
This leads to faster responses and simpler code.
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
