0
0
NestJSframework~3 mins

Why Interceptor interface in NestJS? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to add powerful features everywhere in your app with just one simple interface!

The Scenario

Imagine you want to log every request and response in your server manually by adding logging code inside every controller method.

The Problem

Manually adding logging or modifying behavior in every method is repetitive, easy to forget, and clutters your business logic with extra code.

The Solution

The Interceptor interface lets you write reusable code that runs before and after method calls, keeping your logic clean and consistent.

Before vs After
Before
async getData() { console.log('Start'); const result = await fetchData(); console.log('End'); return result; }
After
@UseInterceptors(LoggingInterceptor) async getData() { return await fetchData(); }
What It Enables

You can cleanly add features like logging, caching, or error handling across many methods without repeating code.

Real Life Example

Logging every API request and response time automatically to monitor performance without touching each controller method.

Key Takeaways

Manual code repetition is slow and error-prone.

Interceptors run code before and after method calls.

They keep your code clean and reusable.