Skip to content
NestPath

Interceptors

The only layer that runs before AND after your controller. Success envelopes, request timing, timeouts, RxJS map vs tap, and Russian-doll execution order.

Alright, you've handled what happens when things go wrong (Exception Filters). Now let's handle what happens when things go right — because right now your successful responses are just as inconsistent as your errors were before.


The Problem You Have Right Now

Your CRUD endpoints currently return raw data:

GET /tasks returns:

json
[
  { "id": 1, "title": "Learn NestJS", "description": "...", "done": false }
]

POST /tasks returns:

json
{ "id": 2, "title": "New task", "description": "...", "done": false }

DELETE /tasks/1 returns:

text
(empty 200 response)

Three endpoints, three different response shapes. No wrapper, no metadata, no consistency. Your error responses now have a beautiful consistent ErrorResponse structure with statusCode, timestamp, path. But your success responses? Raw, naked data flung at the client.

Your React frontend is now doing:

ts
// for list
const tasks = await res.json(); // it's an array... directly?

// for create
const task = await res.json(); // it's an object... directly?

// for delete
// nothing? how do I know it worked?

No success flag, no data wrapper, no way to distinguish between "the API returned an empty array" and "the API is broken." You've spent a decade building products — you know this won't scale.

Analogy

Right now your API ships products loose in the mail truck: sometimes a bare book, sometimes an envelope, sometimes nothing with no receipt. A real store puts every order — big or small — in the same branded box with a packing slip. The customer can tell "empty box, as ordered" apart from "the store forgot to ship" at a glance.


What Interceptors Are

Interceptors are the wrapping layer around your controller execution. They sit in the pipeline and have a unique superpower that no other NestJS construct has — they execute both before AND after the controller method.

Request → Middleware → Guards → INTERCEPTOR (pre) → Pipes → Controller → Service

service returns data

INTERCEPTOR (post)
transforms the response
HTTP Response

Think of an interceptor like a function that wraps your controller call:

ts
// Conceptually, this is what an interceptor does:
function intercept(controllerMethod) {
  // BEFORE controller runs — do stuff here
  console.log('Request coming in...');
  const startTime = Date.now();

  const result = controllerMethod(); // controller + service execute

  // AFTER controller returns — transform result here
  const duration = Date.now() - startTime;
  console.log(`Took ${duration}ms`);

  return wrapInEnvelope(result);
}

In NestJS terms, this "wrapping" is done with RxJS Observables. Don't panic — you don't need to learn RxJS. You need exactly two operators: map (transform the response) and tap (side effects without transforming). That's it.

Analogy

An interceptor is the airport: you pass through it on the way to the plane AND on the way back out. Security notes when you went in, and the same airport hands you your stamped luggage on return. Guards, pipes, and filters each see the request once — only the interceptor is standing there in both directions.


The Interceptor Interface

Every interceptor implements NestInterceptor with one method:

ts
intercept(context: ExecutionContext, next: CallHandler): Observable<any>
  • context: ExecutionContext — Same idea as ArgumentsHost from filters, but with extra methods. Gives you access to the request, the controller class, the handler method, metadata, etc.

  • next: CallHandler — Has one method: next.handle(). This triggers the controller method and returns an Observable of the response. If you never call next.handle(), the controller never executes. This is how interceptors can short-circuit requests.

  • Observable<any> — The return type. You call next.handle() and chain RxJS operators on it to transform what comes out.

ts
intercept(context, next) {
  // ① BEFORE controller — runs immediately
  console.log('before');

  return next.handle().pipe(
    // ② AFTER controller — runs when response is ready
    map(data => ({ wrapped: data })),
  );
}

Everything before next.handle() is pre-controller. Everything inside .pipe() is post-controller. That's the mental model.

Analogy

next.handle() is the boarding gate. Everything you do before opening the gate happens while the passenger is still with you (pre-controller). Whatever you attach with .pipe() is instructions for the arrivals hall — it runs when the passenger comes back through with the response. And if you never open the gate, nobody flies: the controller simply never runs.


Interceptor 1: Response Transformer — Consistent Success Envelope

This is the one you need most. Wrap every successful response in a consistent shape.

First, define the shape

src/common/interfaces/api-response.interface.ts

ts
export interface ApiResponse<T> {
  success: true;
  data: T;
  timestamp: string;
  path: string;
}

Now compare with your error shape:

ts
// Error (from your filter)
{ success: false, statusCode, error, message, details?, timestamp, path }

// Success (from your interceptor)
{ success: true, data, timestamp, path }

Your frontend can now do:

ts
const response = await res.json();
if (response.success) {
  // response.data exists, use it
} else {
  // response.message, response.details exist, show error
}

One check. Every endpoint. Forever.

src/common/interceptors/transform.interceptor.ts

ts
import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable, map } from 'rxjs';
import { Request } from 'express';
import { ApiResponse } from '../interfaces/api-response.interface';

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, ApiResponse<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler<T>,
  ): Observable<ApiResponse<T>> {
    const request = context.switchToHttp().getRequest<Request>();

    return next.handle().pipe(
      map((data) => ({
        success: true as const,
        data,
        timestamp: new Date().toISOString(),
        path: request.url,
      })),
    );
  }
}

What's happening step by step:

POST /tasks with { "title": "Learn interceptors", "description": "..." }
TransformInterceptor.intercept() is called
1
PRE-CONTROLLER

nothing to do here (we only transform output)

2
next.handle() triggers → Pipe validates → Controller runs → Service returns

→ data = { id: 1, title: "Learn interceptors", description: "...", done: false }

3
.pipe(map(data => ...)) wraps the response

Final response:

http
{
  "success": true,
  "data": {
    "id": 1,
    "title": "Learn interceptors",
    "description": "...",
    "done": false
  },
  "timestamp": "2026-02-12T11:00:00.000Z",
  "path": "/tasks"
}

The map operator from RxJS takes whatever the controller returned and transforms it. It's identical to Array.map in concept — take input, return new output. The controller returned a Task object; the interceptor wraps it in an ApiResponse envelope.

Analogy

The transform interceptor is the gift-wrapping counter by the exit. Whatever the shop hands over — one book, a stack of plates, an empty "out of stock" note — it leaves in the same branded box with the same ribbon and a dated receipt taped on top. The shop staff (your controllers) never learn how to wrap; they just hand things over.


Interceptor 2: Logging Interceptor — Timing and Visibility

You want to know how long each request takes and what's being hit. This is where tap shines — side effects without modifying the response.

src/common/interceptors/logging.interceptor.ts

ts
import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  Logger,
} from '@nestjs/common';
import { Observable, tap } from 'rxjs';
import { Request } from 'express';

@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger('HTTP');

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const request = context.switchToHttp().getRequest<Request>();
    const { method, url } = request;
    const now = Date.now();

    // ① PRE-CONTROLLER: log incoming request
    this.logger.log(`→ ${method} ${url}`);

    return next.handle().pipe(
      // ② POST-CONTROLLER: log completion + duration
      tap(() => {
        this.logger.log(`← ${method} ${url} [${Date.now() - now}ms]`);
      }),
    );
  }
}

Server console output:

text
[HTTP] → POST /tasks
[HTTP] ← POST /tasks [12ms]

[HTTP] → GET /tasks
[HTTP] ← GET /tasks [3ms]

[HTTP] → GET /tasks/999
(exception thrown — tap doesn't run on errors, filter handles it)

tap vs map: tap peeks at the data without modifying it — fire-and-forget side effects like logging, metrics, analytics. map transforms the data and returns something new. Use tap when you want to observe, map when you want to change.

What about errors? tap only runs on successful responses. If the controller throws, the Observable errors out, tap is skipped, and the exception filter catches it instead. The pipeline self-routes: success → interceptor post-processing, error → exception filter.

Analogy

tap is the security camera over the conveyor belt: it watches every parcel go by and writes down the time, but never opens one. map is the worker who actually repacks the parcel. Cameras for observing, hands for changing — mixing those two up is how logging code ends up corrupting responses.


Interceptor 3: Timeout Interceptor — Don't Let Requests Hang

A service call hangs forever because of a downstream dependency. Without a timeout, the client waits. And waits. And waits. Your load balancer eventually kills it after 30 seconds. Ugly.

src/common/interceptors/timeout.interceptor.ts

ts
import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
  RequestTimeoutException,
} from '@nestjs/common';
import { Observable, timeout, catchError, TimeoutError, throwError } from 'rxjs';

@Injectable()
export class TimeoutInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(
      timeout(5000), // 5 seconds
      catchError((err) => {
        if (err instanceof TimeoutError) {
          return throwError(() => new RequestTimeoutException(
            'Request timed out — server took too long to respond',
          ));
        }
        return throwError(() => err);
      }),
    );
  }
}

If the controller + service chain doesn't resolve within 5 seconds, RxJS's timeout operator fires, catchError catches the TimeoutError, converts it to a NestJS RequestTimeoutException (408), and your exception filter formats it consistently. You're not adding timeout to yet — your in-memory CRUD resolves instantly — but when you add a database or external API calls later, this saves you.

Analogy

The timeout interceptor is the gate agent who closes boarding at a fixed time. However sympathetic your story, at minute five the door shuts and you're sent back to the desk with a proper rebooking slip (a clean 408), instead of the whole plane full of passengers idling on the tarmac waiting for one person.


Register Interceptors Globally

main.ts — Updated

ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter';
import { TransformInterceptor } from './common/interceptors/transform.interceptor';
import { LoggingInterceptor } from './common/interceptors/logging.interceptor';
import { TimeoutInterceptor } from './common/interceptors/timeout.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Pipes — validate input
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
      forbidNonWhitelisted: true,
      transform: true,
    }),
  );

  // Filters — format errors
  app.useGlobalFilters(new AllExceptionsFilter());

  // Interceptors — wrap responses, log, timeout
  app.useGlobalInterceptors(
    new LoggingInterceptor(),       // runs first (outermost)
    new TransformInterceptor(),     // runs second (innermost)
    new TimeoutInterceptor(),
  );

  await app.listen(3000);
}
bootstrap();

Interceptor execution order — this is important:

When you register multiple interceptors, they nest like Russian dolls (not a flat chain):

LoggingInterceptor PRE
outermost wrapper — first registered
TransformInterceptor PRE
TimeoutInterceptor PRE
innermost — closest to the controller
Controller executes
TimeoutInterceptor POST
unwinds first
TransformInterceptor POST
wraps response
LoggingInterceptor POST

logs duration — sees the final, fully wrapped result

First registered = outermost wrapper. Last registered = closest to the controller. The logging interceptor wraps everything, including the time spent in the transform interceptor. The transform interceptor wraps the raw controller output before logging sees the final result.

Analogy

Think of airport layers on a round trip: you pass check-in, then security, then the gate on the way out — and come back through them in exactly reverse order on the way home. Whichever layer you entered first is the last one you exit. That's why the first-registered interceptor sees the request first and the response last.


Update Exception Filter for Consistency

Your success responses now have success: true. Your errors should have success: false to match. Small update:

src/common/interfaces/error-response.interface.ts

ts
export interface ErrorResponse {
  success: false;
  statusCode: number;
  error: string;
  message: string;
  details?: string[];
  timestamp: string;
  path: string;
}

And in your AllExceptionsFilter, add success: false to the response object:

ts
const errorResponse: ErrorResponse = {
  success: false,       // ← add this
  statusCode: status,
  error: this.getErrorName(status),
  message,
  ...(details && { details }),
  timestamp: new Date().toISOString(),
  path: request.url,
};

Now every response from your API — success or error — starts with success: boolean. Your frontend never guesses.


The Complete Picture — Every CRUD Endpoint Now

GET /tasks — List all

json
{
  "success": true,
  "data": [
    { "id": 1, "title": "Learn NestJS", "description": "CRUD first", "done": false },
    { "id": 2, "title": "Learn interceptors", "description": "wrapping", "done": true }
  ],
  "timestamp": "2026-02-12T11:00:00.000Z",
  "path": "/tasks"
}

GET /tasks/1 — Single task

json
{
  "success": true,
  "data": { "id": 1, "title": "Learn NestJS", "description": "CRUD first", "done": false },
  "timestamp": "2026-02-12T11:00:00.000Z",
  "path": "/tasks/1"
}

POST /tasks — Create (201)

json
{
  "success": true,
  "data": { "id": 3, "title": "New task", "description": "testing", "done": false },
  "timestamp": "2026-02-12T11:00:00.000Z",
  "path": "/tasks"
}

PATCH /tasks/1 — Update

json
{
  "success": true,
  "data": { "id": 1, "title": "Updated title", "description": "CRUD first", "done": true },
  "timestamp": "2026-02-12T11:00:00.000Z",
  "path": "/tasks/1"
}

DELETE /tasks/1 — Delete

json
{
  "success": true,
  "data": null,
  "timestamp": "2026-02-12T11:00:00.000Z",
  "path": "/tasks/1"
}

Wait — data: null on delete? That's because your controller's remove() returns void. The interceptor wraps undefined which serializes to null. If that bothers you, two options:

Option A: Return something from the controller:

ts
@Delete(':id')
remove(@Param('id', ParseIntPipe) id: number): { deleted: boolean } {
  this.tasksService.remove(id);
  return { deleted: true };
}

Now you get "data": { "deleted": true }.

Option B: Handle it in the interceptor:

ts
map((data) => ({
  success: true as const,
  data: data ?? null,  // explicit null, or you could use a message
  timestamp: new Date().toISOString(),
  path: request.url,
})),

Your call. Both are valid. Option A is more explicit.


GET /tasks/999 — Not found (error hits filter, not interceptor)

json
{
  "success": false,
  "statusCode": 404,
  "error": "Not Found",
  "message": "Task with id 999 not found",
  "timestamp": "2026-02-12T11:00:00.000Z",
  "path": "/tasks/999"
}

POST /tasks with bad data — Validation error

json
{
  "success": false,
  "statusCode": 400,
  "error": "Bad Request",
  "message": "Validation failed",
  "details": ["title should not be empty"],
  "timestamp": "2026-02-12T11:00:00.000Z",
  "path": "/tasks"
}

See the pattern? Every response, success or failure, is predictable. Your frontend can type this once and trust it everywhere.


Scope Levels — Just Like Filters

ts
// Global — all routes
app.useGlobalInterceptors(new TransformInterceptor());

// Controller level — all routes in this controller
@Controller('tasks')
@UseInterceptors(TransformInterceptor)
export class TasksController {}

// Route level — this one route
@Get()
@UseInterceptors(TransformInterceptor)
findAll() {}

When to scope? When specific endpoints need different behavior. Maybe your health check endpoint at /health should return raw { status: 'ok' } without the wrapper. You'd exclude it from the global interceptor using a custom decorator or scoping the interceptor to specific modules only. For now, global is fine.

Opting a route out — the @SkipTransform() decorator

Scoping works, but the cleaner pattern (and the one the capstone expects you to own) is a marker decorator the interceptor checks and bows out on. A load balancer hitting /health wants a bare { status: 'ok' }, not your envelope — so you tag that route and the interceptor leaves it alone.

A decorator is just a metadata setter, and the interceptor reads it with Reflector — the exact same mechanism guards use for @Public() in the next module:

ts
// src/common/decorators/skip-transform.decorator.ts
import { SetMetadata } from '@nestjs/common';

export const SKIP_TRANSFORM_KEY = 'skipTransform';
export const SkipTransform = () => SetMetadata(SKIP_TRANSFORM_KEY, true);
ts
// in TransformInterceptor — inject Reflector, then short-circuit the wrapping
constructor(private reflector: Reflector) {}

intercept(context: ExecutionContext, next: CallHandler) {
  const skip = this.reflector.getAllAndOverride<boolean>(SKIP_TRANSFORM_KEY, [
    context.getHandler(),
    context.getClass(),
  ]);
  if (skip) return next.handle();           // pass the raw value straight through

  const request = context.switchToHttp().getRequest<Request>();
  return next.handle().pipe(map((data) => ({ success: true as const, data, /* ... */ })));
}
ts
@SkipTransform()
@Get('health')
health() {
  return { status: 'ok' };   // reaches the client exactly as written
}

Because the interceptor now injects Reflector, register it DI-aware via APP_INTERCEPTOR (below) rather than new TransformInterceptor().

Analogy

The gift-wrapping counter wraps every order by default — but some items arrive with a "no wrapping, leave as-is" sticker (a health probe that just needs a bare yes/no). The clerk sees the sticker and hands it straight over. One glance, no exceptions carved into the counter's routine.

The other way to extend the envelope: pagination meta

@SkipTransform removes the envelope for one route. The opposite move is to enrich it. A list endpoint shouldn't just hand back an array — the client needs to know the total count and which page it's on. That metadata doesn't belong inside data (that's your rows); it belongs beside it, as meta.

Have the list controller return the raw ingredients, and a route-scoped interceptor reshape them into the envelope:

ts
// controller — return items + counts (route-scoped interceptor does the wrapping)
@Get()
@UseInterceptors(PaginateInterceptor)
findAll(@Query() query: QueryTasksDto) {
  return this.tasksService.findAll(query); // → { items, total, page, limit }
}
ts
// PaginateInterceptor — lift total/page/limit out to meta, keep items as data
return next.handle().pipe(
  map(({ items, total, page, limit }) => ({
    success: true as const,
    data: items,
    meta: { total, page, limit },   // ← the extra shelf beside the box
    requestId: request['requestId'],
    timestamp: new Date().toISOString(),
    path: request.url,
  })),
);

Now GET /tasks?page=2&limit=10 returns { success, data: [...], meta: { total: 57, page: 2, limit: 10 }, ... } — the frontend can render "Page 2 of 6" without a second request. The capstone's board-list endpoint expects exactly this shape.

Analogy

A single item ships in the branded box. A bulk order ships in the same box plus a packing slip taped to the side — quantity, page X of Y, what's still on backorder. The contents (data) and the paperwork about the shipment (meta) travel together but never get mixed into the same compartment.


DI-Aware Registration — Same Pattern as Filters

ts
// app.module.ts
import { APP_INTERCEPTOR } from '@nestjs/core';

@Module({
  providers: [
    {
      provide: APP_INTERCEPTOR,
      useClass: LoggingInterceptor,
    },
    {
      provide: APP_INTERCEPTOR,
      useClass: TransformInterceptor,
    },
  ],
})
export class AppModule {}

Same reason as filters — if your interceptor needs to inject ConfigService, CacheService, or anything else, it needs to live in the DI container.


Updated Project Structure

src
app.module.ts
main.ts
common
filters
all-exceptions.filter.ts
interceptors
transform.interceptor.ts
logging.interceptor.ts
timeout.interceptor.ts
interfaces
api-response.interface.ts
error-response.interface.ts
exceptions
task-not-found.exception.ts
tasks
tasks.module.ts
tasks.controller.ts
tasks.service.ts
dto
create-task.dto.ts
update-task.dto.ts
interfaces
task.interface.ts

The Full Pipeline — Where Everything Sits Now

Incoming HTTP Request
MIDDLEWARE
Express-level: cors, body-parser, etc.
GUARDS
auth — not yet implemented
INTERCEPTORS PRE

LoggingInterceptor logs "→ GET /tasks"
TransformInterceptor (nothing to do pre)
TimeoutInterceptor starts the clock

PIPES

ValidationPipe validates DTOs, ParseIntPipe converts params

CONTROLLER
thin, delegates to service
SERVICE
business logic, returns data or throws
INTERCEPTORS POST

TimeoutInterceptor (didn't timeout, good)
TransformInterceptor wraps { success, data, ... }
LoggingInterceptor logs "← GET /tasks [5ms]"

HTTP Response

If an exception is thrown anywhere above:

EXCEPTION FILTER

AllExceptionsFilter formats { success: false, ... }

HTTP Error Response
⚡ Quick lookup — pipeline in one line
text
Request -> Middleware -> Guards -> Interceptors(pre: Logging, Transform, Timeout)
        -> Pipes -> Controller -> Service
        -> Interceptors(post: Timeout, Transform, Logging) -> Response
        (exception anywhere -> AllExceptionsFilter -> error response)

Every layer you've built slots in cleanly. Controller and service code remain untouched from lesson one. You've added validation, error formatting, response wrapping, logging, and timeouts — all without modifying a single line in your business logic. That's the architecture paying off.


Next up when you're ready: Guards — authentication and authorization, the layer that decides "should this request even be allowed to proceed?" before anything else meaningful happens.