04 / 06

How do you implement a caching interceptor that short-circuits the handler in NestJS?

Return a cached observable before calling next.handle() to bypass the controller handler entirely. Calling next.handle() is what actually invokes the handler — returning an observable without calling it means the handler is skipped. Store the result with tap() after the first real invocation.

Short-circuiting cache interceptor
Key concepts behind short-circuiting:
  1. 1

    next.handle() is a lazy Observable — calling it is what invokes the controller handler.

  2. 2

    Returning of(cachedValue) before calling next.handle() skips the handler entirely.

  3. 3

    tap() is used to store the result after the first real handler execution.

  4. 4

    This is the exact mechanism behind NestJS @nestjs/cache-manager CacheInterceptor.

  5. 5

    For production caching use @nestjs/cache-manager with TTL and Redis backend.