0
0
NestJSframework~3 mins

Why interceptors add cross-cutting logic in NestJS - The Real Reasons

Choose your learning style9 modes available
The Big Idea

Discover how one simple tool can save you from endless repetitive code and bugs!

The Scenario

Imagine you have to add logging, error handling, and timing to every function in your NestJS app manually by writing the same code inside each controller or service method.

The Problem

Manually adding these repeated tasks everywhere makes your code messy, hard to maintain, and easy to forget or make mistakes. It slows you down and causes bugs.

The Solution

Interceptors let you write this shared logic once and apply it automatically across many parts of your app, keeping your code clean and consistent.

Before vs After
Before
async getData() {
  console.log('Start');
  try {
    const result = await this.service.fetch();
    console.log('End');
    return result;
  } catch (e) {
    console.error(e);
    throw e;
  }
}
After
@UseInterceptors(LoggingInterceptor)
async getData() {
  return this.service.fetch();
}
What It Enables

You can add or change shared behaviors like logging, caching, or error handling in one place and have it affect your whole app automatically.

Real Life Example

In a real app, you might want to log every request's duration to find slow endpoints without touching each controller method.

Key Takeaways

Manual repetition of shared logic is error-prone and hard to maintain.

Interceptors centralize cross-cutting concerns for cleaner code.

This makes your app easier to update and debug.