In a NestJS 12 interceptor, what does CallHandler.handle() return, and how do you time or reshape a handler's result with RxJS?
answer
- wraps the handler, before and after
- a cold stream Nest subscribes to
- tap, map, finalize, timeout
- no handle() call, no handler
basics
~20 snext.handle() returns an RxJS Observable of the route handler's result, and the handler runs only once Nest subscribes to the stream intercept() returns. Code before handle() runs first; operators such as map, finalize and timeout act on the result afterwards.
solid answer
~40 sAn interceptor implements `NestInterceptor`: `intercept(context, next)` gets the same `ExecutionContext` a guard gets plus a `CallHandler`. `next.handle()` returns an `Observable` that emits whatever the handler returns; Nest subscribes to the stream your `intercept()` returns, and only then does the handler run. If you never call `handle()`, the handler never runs, which is how a cache interceptor answers with `of(cached)`. Logic placed before `handle()` runs before the handler; logic piped onto the stream runs after it: `map()` reshapes the result, `catchError()` swaps an exception, `timeout()` plus `catchError()` turns a slow handler into a `RequestTimeoutException`. For timing, prefer `finalize()`, because `tap(fn)` skips the error path. Two caveats: a handler that sends through `@Res()` without `passthrough` bypasses the stream, and `timeout()` stops waiting but does not cancel the handler's work.
code
typescript · 25 linesimport {
CallHandler,
ExecutionContext,
Injectable,
Logger,
NestInterceptor,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { finalize } from 'rxjs/operators';
@Injectable()
export class TimingInterceptor implements NestInterceptor {
private readonly logger = new Logger(TimingInterceptor.name);
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
const route = `${context.getClass().name}.${context.getHandler().name}`;
const started = performance.now();
return next.handle().pipe(
finalize(() => {
const ms = (performance.now() - started).toFixed(1);
this.logger.log(`${route} took ${ms}ms`);
}),
);
}
}go deeper
Recall that an interceptor wraps the handler: code before next.handle() runs first, and operators piped onto its Observable run on the result.
Explain why the handler runs only on subscription, why skipping handle() replaces the handler, and when to use map, tap, finalize, catchError and timeout.
Spot the timing interceptor that misses failed requests, the 408 that leaves a query running, and the @Res() route that silently escapes response mapping.
Decide which concerns a team puts in global interceptors (timing, envelopes, timeouts) and how they stay cheap and observable when every request passes through them.
## The interceptor contract A NestJS **interceptor** is an `@Injectable()` class implementing `NestInterceptor` from `@nestjs/common`. Its one method is: ```typescript intercept(context: ExecutionContext, next: CallHandler): Observable<any> | Promise<Observable<any>>; ``` - `context` is an `ExecutionContext`, the same object guards receive, so `context.getHandler()` and `context.getClass()` identify the route and `Reflector` can read its metadata. - `next` is a `CallHandler` whose only method, `handle()`, returns an RxJS `Observable` of the value the route handler returns. - `intercept()` may be `async` when it must await something before returning the stream. The documentation borrows the aspect-oriented term **pointcut** for the `handle()` call: the point where the interceptor's extra logic meets the handler. ## Before and after, in order 1. Code in `intercept()` before `next.handle()` runs first, with the request available through the context. 2. `next.handle()` returns a stream but does not yet run the handler. 3. Nest subscribes to the stream `intercept()` returned; that subscription runs the handler. 4. The handler's return value (or its awaited promise) flows through the operators you piped onto the stream. 5. Whatever the final stream emits becomes the response body; an error it carries goes to the exceptions layer. Because the handler only runs through that subscription, an interceptor that returns a different stream without calling `handle()` **replaces** the handler entirely. ## The operators that matter | Operator | What it does in an interceptor | |---|---| | `tap(fn)` | side effect on the emitted value; the function is skipped when the handler throws | | `tap({ next, error })` | side effects on success and on error | | `finalize(fn)` | runs on completion, error or unsubscription, the safe place to stop a timer | | `map(fn)` | replaces the emitted value, e.g. wrapping it as `{ data }` | | `catchError(fn)` | swaps an error, e.g. for a `BadGatewayException` | | `timeout(ms)` | fails the stream with `TimeoutError` if nothing arrives in time | | `of(value)` | a ready-made stream, used to answer without running the handler | ## A timing interceptor that also times failures The documentation's `LoggingInterceptor` measures with `tap(() => ...)`. That callback fires only when the handler emits a value, so a request that throws leaves no timing line, which is exactly the request you wanted to see. Using `finalize()` closes that gap: it runs whether the stream completes, errors or is unsubscribed. The code example below does this and labels each line with `getClass().name` and `getHandler().name`. ## Reading the route inside an interceptor An interceptor gets the full `ExecutionContext`, so it can do more than wrap the stream: - `context.getClass().name` and `context.getHandler().name` label log lines and metrics per route, as the timing example does. - `context.getType()` tells an interceptor shared with microservice or WebSocket handlers whether it is in `'http'`, `'rpc'` or `'ws'`, before it calls `switchToHttp()`. - An injected `Reflector` reads per-route metadata, so a decorator can switch the interceptor's behaviour off or tune it for one handler, for example a longer timeout on an export endpoint. The documentation suggests exactly this pairing for turning its cache example into a generic solution. ## Things that bite - **Library-specific responses.** A handler that injects `@Res()` and calls `res.json()` itself returns nothing into the stream, so `map()` has nothing to transform. Nest documents that response mapping does not work in that mode unless the handler uses `@Res({ passthrough: true })` and returns its value. - **`timeout()` does not cancel work.** It unsubscribes from the handler's stream and, through `catchError()`, can turn `TimeoutError` into `RequestTimeoutException` (408). A promise the handler already started, such as a database query, keeps running; release resources yourself if that matters. - **Operators run per emitted value.** A handler that returns a value or a promise emits exactly one; keep that in mind before writing operators that assume otherwise. - **Forgetting to return the stream.** `intercept()` must return the piped `Observable`; building it and returning something else drops your operators. ## Binding Interceptors bind like guards: `@UseInterceptors(TimingInterceptor)` on a method or controller (a class, so Nest injects its dependencies, or an instance you build), `app.useGlobalInterceptors(new TimingInterceptor())` for a global instance without injection, or a provider `{ provide: APP_INTERCEPTOR, useClass: TimingInterceptor }` for a global interceptor the container builds.
- Why does a NestJS timing interceptor built with tap(() => log()) write nothing for requests whose handler threw?`tap()` with a single function reacts only to emitted values. When the handler throws, the stream carries an error notification instead, so the callback is skipped. Pass an observer, `tap({ next, error })`, or use `finalize()`, which runs on completion, error and unsubscription. Timing only the successful calls hides the slowest failures from the logs.
- When a NestJS interceptor's timeout() fires, does the route handler stop?No. `timeout()` errors the stream and unsubscribes from the handler's result, so the client can get a `RequestTimeoutException` (408) right away, but a promise the handler already started, such as a pending query, keeps running and its late result is discarded. The documentation says to add your own logic to release resources if you need to.
- Why does a NestJS interceptor's map() leave a response untouched when the handler uses @Res()?A handler that injects `@Res()` and calls `res.json()` itself has taken over the response, so it returns nothing into the stream and `map()` has no value to change. Nest disables standard response handling for that route. Use `@Res({ passthrough: true })` and return the value, and interceptors apply again.
- next.handle() runs the route handler immediately and returns its plain value.
- A tap() callback also runs when the route handler throws an exception.
- When timeout() fires, Nest aborts the handler's pending database query.
- An interceptor that never calls next.handle() still lets the handler run afterwards.
- A map() interceptor also reshapes a body the handler sent with res.json() through @Res().