Skip to content
NestPath

Exercises — Interceptors

Covers: pre/post execution model, NestInterceptor interface, ExecutionContext + CallHandler, next.handle() and short-circuiting, RxJS map vs tap, TransformInterceptor (success envelope), LoggingInterceptor (timing), TimeoutInterceptor (RxJS timeout + catchError → 408), Russian-doll registration order, error-path routing to filters, success:false filter alignment, data: null on void, scoping, APP_INTERCEPTOR.


Part A — Concept Checks (closed book)

  1. What is the one superpower interceptors have that no other NestJS construct has?
  2. In intercept(context, next), what code region is "pre-controller" and what region is "post-controller"?
  3. What happens if you never call next.handle()? What could that be used for?
  4. map vs tap — define each, name the interceptor from the lesson that uses each, and say which one is allowed to change the response.
  5. If the controller throws, does tap in a logging interceptor run? What handles the response instead?
  6. Interceptors registered as LoggingInterceptor, TransformInterceptor, TimeoutInterceptor — draw the Russian-doll nesting. Which one's PRE runs first? Which one's POST runs first?
  7. Why does DELETE return "data": null after the TransformInterceptor is added? Give both fixes from the lesson.
  8. Why must the ErrorResponse interface gain success: false in this module? What one-check pattern does the frontend get?
  9. How does the TimeoutInterceptor convert an RxJS TimeoutError into a proper HTTP 408, and who formats the final response body?
  10. Why is the interceptor's measured duration smaller than what a middleware-level logger (Module 06) will measure?
  11. When would you scope an interceptor to a route rather than global? Give the lesson's example.
  12. What does APP_INTERCEPTOR registration buy you over useGlobalInterceptors(new ...)?

Part B — Guided Exercises

B1. TransformInterceptor

  1. Create ApiResponse<T> interface (success: true, data, timestamp, path).
  2. Implement TransformInterceptor<T> with map.
  3. Register globally. Verify all five task endpoints now return the envelope; capture the DELETE response and observe data: null.
  4. Fix DELETE with Option A (controller returns { deleted: true }).
  5. Add success: false to ErrorResponse + the filter. Verify a 404 and a 200 side by side — every response now starts with success.

B2. LoggingInterceptor

  1. Implement with Logger('HTTP'), pre-log → METHOD URL, tap post-log ← METHOD URL [Xms].
  2. Trigger a 404 and confirm the console shows the → line but no ← line. Write one sentence explaining why.

B3. TimeoutInterceptor

  1. Implement with timeout(5000) + catchError → RequestTimeoutException.
  2. Prove it works: temporarily add to a service method await new Promise((r) => setTimeout(r, 6000)); (make the method async).
  3. Verify the client receives your standard envelope: success: false, statusCode: 408. Then remove the sleep.
  4. Register all three interceptors in the lesson's order and confirm log timing includes transform time.

B4. Order experiment

Swap registration to TransformInterceptor, LoggingInterceptor. Add a tap(data => console.log(data)) in the logging interceptor. What does it see now — raw controller output or the envelope? Reconcile with the Russian-doll rule, then restore the original order.


Part C — Independent Challenges

C1. Pagination envelope

For GET /tasks only (route-scoped interceptor via @UseInterceptors), extend the envelope with meta: { total, page, limit }. The controller returns { items, total, page, limit }; the interceptor reshapes to { success, data: items, meta, timestamp, path }. Combine with Module 02's QueryTasksDto.

C2. Cache interceptor (short-circuit)

Build CacheInterceptor for GET requests: an in-memory Map<url, {data, expires}> with 30s TTL. On hit → return of(cachedData) without calling next.handle() (import of from rxjs). On miss → next.handle().pipe(tap(save)). Prove it: add a console.log in the service and watch it fire only on cache misses. Bonus: bust the cache for /tasks* whenever a POST/PATCH/DELETE succeeds.

C3. Slow-request alarm

A PerformanceInterceptor that logs at warn level whenever any request exceeds 500ms, including method, url, and duration. Decide and justify: does this replace the LoggingInterceptor or complement it?

C4. Response versioning header

An interceptor that sets X-API-Version: 1.0 on every response (hint: you need context.switchToHttp().getResponse() and setHeader — headers are a side effect, so pick tap or do it pre-handle; justify your choice).


Part D — Debug Drills

D1

ts
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
  console.log('before');
  next.handle();
  return next.handle().pipe(map(d => ({ success: true, data: d })));
}

Symptom: service logic (and DB writes, later) execute twice per request. Why?

D2

ts
return next.handle().pipe(
  map(data => {
    this.logger.log('response ready');   // side effect inside map
    // forgot to return
  }),
);

Symptom: every endpoint returns "data": undefined… actually the whole body is empty. Two problems — name both and the idiomatic fix.

D3

ts
app.useGlobalInterceptors(new TransformInterceptor());

plus in AppModule: { provide: APP_INTERCEPTOR, useClass: TransformInterceptor }. Symptom: responses look like { success: true, data: { success: true, data: {...} } }. Explain.

D4

ts
return next.handle().pipe(
  timeout(5000),
  map(data => wrap(data)),
  catchError(err => of({ success: false, message: err.message })),
);

Symptom: errors now return HTTP 200 with an error-ish body, and the exception filter never runs. What did catchError + of do to the error channel, and when is swallowing like this ever acceptable?

D5

ts
@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context, next) {
    const request = context.switchToHttp().getRequest();
    return next.handle().pipe(
      map(data => ({ success: true, data, path: request.url, timestamp: new Date().toISOString() })),
    );
  }
}

A teammate claims the timestamp is "when the request arrived." True or false — when does the map callback body actually execute? Design a 2-line experiment to prove it.


Part E — Prediction Drills

Full stack so far: validation + filter (success:false) + Logging→Transform→Timeout interceptors. Predict the exact body:

  1. GET /tasks when the array is empty.
  2. POST /tasks with an invalid body — does the response contain the interceptor's envelope, the filter's envelope, or both?
  3. GET /tasks/1 where the service takes 6s.
  4. Controller returns the string "pong" from a new GET /ping — what's data?
  5. The LoggingInterceptor console for scenario 3 — is there a ← line?

Part F — Stretch Goals

  1. Exclusion mechanism: a @SkipTransform() decorator (SetMetadata — Module 05 preview) that the TransformInterceptor reads via Reflector to bypass wrapping for /health.
  2. Read about RxJS finalize — rewrite the logging interceptor so the duration line fires on success and error paths. Compare with the middleware logger's role.
  3. Streaming caveat: research why response-transforming interceptors and @Res() (manual response handling) don't mix.

Self-Assessment Checklist

  • I can write an interceptor from memory: signature, next.handle(), .pipe()
  • I know exactly what runs pre vs post, and can predict nesting for N interceptors
  • I can choose map vs tap correctly on the first try
  • Success and error responses share the success discriminator
  • I have short-circuited a request from an interceptor (cache) and understand the power/danger
  • I verified the error path skips post-interceptor logic and lands in the filter

Answers & Hints

A1: They execute both before AND after the controller — they wrap handler execution.

A2: Everything before return next.handle() = pre. Everything inside .pipe(...) operators = post.

A3: The controller never executes; the request is short-circuited. Use: caching, mocking, feature-flag rejection.

A4: map transforms and returns new data (TransformInterceptor). tap observes without modifying (LoggingInterceptor). Only map changes the response.

A5: No — on error the Observable errors out, tap is skipped, the exception filter formats the response.

A6: Logging(pre) → Transform(pre) → Timeout(pre) → controller → Timeout(post) → Transform(post) → Logging(post). First registered = outermost: its PRE runs first, its POST runs last. (So the first-POST-to-run is the last-registered, Timeout.)

A7: remove() returns void → undefined → JSON null inside the wrapper. Fix A: return { deleted: true } from the controller. Fix B: data: data ?? null (or a message) in the interceptor.

A8: So success: boolean becomes the single discriminator; frontend does if (response.success) and never guesses shapes again.

A9: timeout(5000) emits TimeoutError → catchError re-throws RequestTimeoutException (408) via throwError → exception filter formats the envelope.

A10: Interceptors wrap only controller+service (plus inner interceptors). Middleware res.on('finish') spans the entire pipeline including guards, serialization, and outer layers.

A11: A route needing different behavior — e.g., /health returning raw {status:'ok'} without the wrapper.

A12: DI: the interceptor can inject ConfigService/CacheService/etc.

D1: next.handle() was called twice; each call triggers handler execution when subscribed. Cold-observable behavior + double invocation = duplicated side effects.

D2: (1) map callback returns undefined (missing return). (2) Side-effect logging belongs in tap, not map. Fix: tap(() => log) then map(data => envelope) — or return the envelope from map.

D3: The interceptor is registered twice (manual + DI). Interceptors nest, so the envelope gets wrapped by the second instance. Pick one registration.

D4: catchError caught ALL errors and replaced the error channel with a normal emission (of(...)) → the Observable completes successfully → 200, filter bypassed. Acceptable only when intentionally converting specific errors into fallback data (e.g., cache-miss defaults) — and even then, re-throw everything else like the TimeoutInterceptor does.

D5: False — map runs post-controller; the timestamp is when the response was ready. Experiment: log Date.now() before next.handle() and inside map around a setTimeout service; compare.

E1: { "success": true, "data": [], "timestamp": ..., "path": "/tasks" } — empty array is a valid success, distinguishable from an error. That's the point.

E2: Only the filter's envelope (success: false...). The transform's map never runs on the error path.

E3: { "success": false, "statusCode": 408, "error": ..., "message": "Request timed out — server took too long to respond", ... }.

E4: "data": "pong" — map wraps whatever the controller returned, primitives included.

E5: No ← line — tap skipped on error. (The middleware logger of Module 06 is what will still capture it.)