Dev.to WebDev 🛠 Dev 👁 0 📖 3 min read

Every response from my API looks the same, and it's two small files: NestJS interceptors in a real project

I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a Python AI service), and it's about the two smallest files in the r

I'm a junior full-stack developer from Alexandria, Egypt. This is another post about FaceMark, my face-recognition attendance system (a NestJS API plus a Python AI service), and it's about the two smallest files in the repo that touch every request: the interceptors.

The problem they solve

An API with twenty endpoints drifts. One controller returns the entity, another returns { message: "ok" }, a third returns whatever the service felt like. The frontend ends up with a different parsing rule per screen, and nobody knows how slow anything is until a user complains.

NestJS's answer is interceptors: code that wraps every handler, sees the request going in and the response going out, and can transform either. FaceMark uses two.

One response shape for everything

// src/common/interceptors/transform.interceptor.ts
export interface Response<T> {
  success: boolean;
  data: T;
  timestamp: string;
}

@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, Response<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<Response<T>> {
    return next.handle().pipe(
      map((data) => ({
        success: true,
        data: data || null,
        timestamp: new Date().toISOString(),
      })),
    );
  }
}

Thirty lines, and every successful response from every endpoint now looks like { success: true, data: ..., timestamp: ... }. The frontend writes its parsing logic once. next.handle() is the actual controller doing its work; the interceptor just maps over what comes back.

The honest limitation I learned while writing this: it only wraps successful responses. Errors go through the exception filter instead, which is a separate piece with its own shape. So "every response looks the same" really means "every response has a defined shape", and there are two of them.

Free request timing

// src/common/interceptors/logging.interceptor.ts
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
  private readonly logger = new Logger('HTTP');

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

    return next.handle().pipe(
      tap((data) => {
        const response = context.switchToHttp().getResponse();
        this.logger.log(
          `${method} ${url} ${response.statusCode} - ${ip} - ${Date.now() - now}ms`,
        );
      }),
    );
  }
}

Every request gets one log line: method, URL, status, IP, and milliseconds. No APM tool, no dashboard, no config. When I was tuning the face-recognition call, the one that goes out to the Python service, these lines were how I saw the difference between a 40ms cache hit and a multi-second AI call without touching the endpoints themselves.

That's the real pitch for interceptors as a junior: cross-cutting concerns (logging, shaping, timing) live in one place, and your controllers stay about the business.

What I'd tell another junior dev

If you copy-paste response formatting into a second controller, stop and write an interceptor. The second copy is when it becomes a convention; the third is when it becomes a bug farm.

tap vs map matters. tap observes (logging), map changes (transform). Mixing them up is the classic first interceptor bug: logging inside a map that forgets to return the data.

Interceptors run outside-in, then inside-out. If you stack two, the first one registered sees the request first and the response last. Worth knowing before you wonder why your log line includes or excludes the transform step.

Everything above is from the real repo.

I'm a junior full-stack developer (Angular, NestJS, TypeScript, Python) in Alexandria, Egypt, open to junior roles and freelance work. More posts from this project:

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.