Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 42 ยท The Request Pipeline

Interceptors

Learn NestJS interceptors: NestInterceptor and CallHandler, RxJS pipe basics, and how to log, time, reshape responses, cache and time out handlers.

An interceptor wraps a route handler. It can run code before the handler, run code after it, change the value the handler returns, change or replace an error, or skip the handler altogether and answer from somewhere else, such as a cache. If a guard is a bouncer at the door, an interceptor is a wrapper around the whole conversation.

That "around" shape is what makes interceptors a good fit for cross-cutting behavior: logging how long each request took, wrapping every response in a standard envelope, caching, retrying, and applying a time limit. They run after guards and before pipes on the way in, and the response flows back out through them in reverse order.

Real Nest interceptors use RxJS, a library for streams of values. You need only a few operators, and this lesson explains them. The Nest code is read-only here (it needs Node, npm and rxjs). The runnable parts are stand-ins that express the same wrapping idea with promises instead of observables, and they say so where it matters.

What can an interceptor do?

Measure Time every handler.
Reshape Wrap results in an envelope.
Short-circuit Answer from a cache.
Limit Time out slow handlers.
1 / 2

The shape of an interceptor

TypeScript
import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common';
import { Observable, tap } from 'rxjs';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const started = Date.now();
    const route = `${context.getClass().name}.${context.getHandler().name}`;

    return next.handle().pipe(
      tap(() => console.log(`${route} finished in ${Date.now() - started}ms`)),
    );
  }
}

There are two parameters. context is the same ExecutionContext guards get: it tells you the class, the handler and the request. next is a CallHandler, and calling next.handle() is what runs the rest of the pipeline and the route handler. It returns an Observable of the handler's result.

Everything above the return runs before the handler. Everything inside .pipe(...) runs after the handler produces a value. If you never call next.handle(), the handler never runs, which is how a cache short-circuits.

RxJS in five minutes

An Observable is a lazy stream of values. For an ordinary controller it emits exactly one value, the returned data, and then completes. .pipe() chains operators, which transform what flows through:

Operator What it does Typical use
tap(fn) Runs a side effect and passes the value on unchanged Logging, metrics
map(fn) Transforms the value Response envelopes
catchError(fn) Handles or replaces an error Translating errors
timeout(ms) Fails with TimeoutError if no value arrives in time Time limits
of(value) Creates an observable that emits a value Returning a cached value

Laziness is the key point: the handler is not called when you create the pipe; it runs when Nest subscribes. That is why returning of(cached) without calling next.handle() really does skip the handler. If you are comfortable with promises, think of next.handle() as "call the next function", and of map and tap as .then(...).

Common interceptors

Response mapping. Return the same envelope shape from every endpoint:

TypeScript
@Injectable()
export class EnvelopeInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(map((data) => ({ data, ok: true })));
  }
}

Caching. Answer from memory when you can:

TypeScript
@Injectable()
export class MemoInterceptor implements NestInterceptor {
  private readonly store = new Map<string, unknown>();

  intercept(context: ExecutionContext, next: CallHandler) {
    const req = context.switchToHttp().getRequest();
    if (req.method !== 'GET') return next.handle();

    const key = req.originalUrl;
    if (this.store.has(key)) return of(this.store.get(key));

    return next.handle().pipe(tap((value) => this.store.set(key, value)));
  }
}

This hand-rolled cache has no expiry and no size limit, so it is only a teaching example. Real apps use the CacheModule and CacheInterceptor covered in Caching, Throttling and Scheduling.

Timeouts. Give up on slow handlers and translate the RxJS error into an HTTP one:

TypeScript
@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(
      timeout(5000),
      catchError((err) =>
        err instanceof TimeoutError
          ? throwError(() => new RequestTimeoutException())
          : throwError(() => err),
      ),
    );
  }
}

Note that a timeout stops waiting for the result; it does not necessarily cancel work the handler already started, such as a database query.

Nest also ships ClassSerializerInterceptor, which applies class-transformer rules (like hiding a password field) to returned objects.

Binding and order

Like guards, interceptors bind with @UseInterceptors() on a method or controller, globally with app.useGlobalInterceptors(...), or as a provider using the APP_INTERCEPTOR token when they need injection.

When several apply, the before parts run global, then controller, then route. The after parts run in the opposite order, like nested function calls or Russian dolls: the interceptor closest to the handler sees the raw result first, and the outermost one sees the final shape last. That is why an envelope interceptor registered globally wraps whatever the route-level ones produced.

The handler's errors also travel back through the interceptors, so catchError can translate them before exception filters see them. Order of everything in the request pipeline is summarized in the middleware lesson.

Stand-in: wrapping handlers with promises

This is not RxJS. It models an interceptor as (ctx, next) => promise, where next() calls the rest of the chain. Interceptors are composed outermost first, so you can see before and after steps nest. The timing check prints a boolean instead of a number to stay deterministic.

JS Interceptors as nested wrappers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The trace is symmetrical: timing, envelope and upper run their "before" parts in listed order, then the handler, then their "after" parts in reverse. upper sees the raw string first, then envelope wraps it, and timing measures the whole thing.

Stand-in: cache and timeout

The second stand-in implements the two interceptors that change the flow instead of just decorating the result: a cache that skips the handler, and a timeout that stops waiting. The handler is slow on purpose so the effects are visible without relying on exact numbers.

JS A cache that skips and a timeout that gives up

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second /cats request is answered with cached: true and the handler is not called again (the call count stays at 1). The /slow request exceeds 30 ms, so the wrapper rejects with a 408-style error even though the handler itself keeps running in the background, which is the same limit a real timeout operator has.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must an interceptor do for the route handler to run?

    next.handle() continues the pipeline and runs the handler. If you never call it, for example when returning a cached of(value), the handler is skipped.
  2. 2. Which RxJS operator is the right tool to run a side effect such as logging without changing the value?

    tap observes the value and passes it through unchanged. map would replace it with whatever you return.
  3. 3. Three global interceptors A, B, C are listed in that order. In what order do their post-handler parts run?

    Responses unwind through the interceptors in reverse order: C is closest to the handler, A is outermost.
  4. 4. A timeout(5000) interceptor fires while a handler is running a slow database query. What is guaranteed?

    A timeout limits how long the response waits. Cancelling the underlying work needs separate support such as abort signals or driver timeouts.

Summary

  • An interceptor implements NestInterceptor.intercept(context, next) and wraps the handler: code before next.handle() runs on the way in, operators in .pipe() run on the way out.
  • Skip next.handle() and return of(value) to short-circuit, for example from a cache.
  • The handful of RxJS operators you need are tap, map, catchError, timeout and of.
  • Bind with @UseInterceptors(), useGlobalInterceptors() or APP_INTERCEPTOR; the after-phase runs in reverse order.
  • Use interceptors for logging, timing, response envelopes, caching and time limits, not for access control.

Next, decide what clients see when something goes wrong in Exception Filters and Errors.