Implement Cache Interceptor in Nest.js with Redis

Akifcan Kara
1 min readOct 20, 2022
  • Use a cache interceptor that cache your every request.

Hello,

In this article I’d like to show you how you can implement a cache interceptor in Nest.js using Redis.

Note: Make sure you have set up redis before use this interceptor.

  • Line 7: First we injected redis service. Aka cache service https://docs.nestjs.com/techniques/caching
  • Line 10: For avoid some unexcepted bugs I disabled this interceptor in dev mode.
  • Line 16: I get the requested url. If url has params request._parsedOriginalUrl?.path will run otherwise request.path will run.
  • Line 17: I checked. If this key exists in redis cache.
  • Line 18–20: If data variable is not undefined then I returned the cached value from redis.
  • Line 23: If data variable is undefined then I let the controller code run.
  • Line 26: After controller runned I saved the page url as key and saved the returned value (from controller) as value.

--

--