0
0
NestJSframework~30 mins

Cache interceptor in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Cache Interceptor in NestJS
📖 Scenario: You are building a simple NestJS API that returns user data. To improve performance, you want to add caching so repeated requests return faster.
🎯 Goal: Build a NestJS cache interceptor that caches the response of a controller method.
📋 What You'll Learn
Create a cache interceptor class that implements NestInterceptor
Add a cache time-to-live (TTL) configuration variable
Use the cache manager to store and retrieve cached responses
Apply the cache interceptor to a controller method
💡 Why This Matters
🌍 Real World
Caching API responses improves performance and reduces server load in real-world web applications.
💼 Career
Understanding interceptors and caching is important for backend developers working with NestJS or similar frameworks.
Progress0 / 4 steps
1
Create the Cache Interceptor Class
Create a class called CacheInterceptor that implements NestInterceptor from @nestjs/common. Import Injectable and decorate the class with it.
NestJS
Need a hint?

Use implements NestInterceptor and decorate the class with @Injectable().

2
Add Cache TTL Configuration
Inside the CacheInterceptor class, add a private readonly property called ttl and set it to 30 (seconds).
NestJS
Need a hint?

Declare private readonly ttl = 30; inside the class but outside the intercept method.

3
Implement Cache Logic in Intercept Method
In the intercept method, import ExecutionContext and CallHandler from @nestjs/common. Use next.handle() to get the response stream. For now, just return next.handle() without caching.
NestJS
Need a hint?

Make sure to type the parameters as ExecutionContext and CallHandler, and return next.handle().

4
Apply Cache Interceptor to Controller Method
Create a controller class called UserController with a method getUser that returns a string 'User data'. Import and apply the CacheInterceptor to the getUser method using the @UseInterceptors(CacheInterceptor) decorator.
NestJS
Need a hint?

Use @UseInterceptors(CacheInterceptor) above the getUser method and return the exact string 'User data'.