📖 Scenario: You are building a NestJS backend application that needs to log the time taken by each request and modify the response before sending it back.This is a common real-world need where you want to add behavior that applies to many parts of your app without changing each controller method.
🎯 Goal: Build a simple NestJS interceptor that adds cross-cutting logic to log request duration and modify the response message.
📋 What You'll Learn
Create a basic NestJS controller with one GET route returning a string
Create an interceptor class implementing NestInterceptor
Add logic in the interceptor to log the time taken for the request
Modify the response data in the interceptor before sending it back
Apply the interceptor to the controller route
💡 Why This Matters
🌍 Real World
In real backend applications, interceptors help add features like logging, caching, or transforming responses without repeating code in every controller method.
💼 Career
Understanding interceptors is important for backend developers working with NestJS or similar frameworks to write clean, maintainable, and scalable server-side code.
Progress0 / 4 steps
1
Create a basic NestJS controller
Create a NestJS controller class called AppController with a GET route method getHello that returns the string 'Hello World'.
NestJS
Hint
Use @Controller() decorator and define a method getHello with @Get() decorator returning the exact string.
2
Create an interceptor class
Create a class called LoggingInterceptor that implements NestInterceptor from @nestjs/common. Import CallHandler and ExecutionContext as well. Add an empty intercept method with parameters context: ExecutionContext and next: CallHandler returning next.handle().
NestJS
Hint
Implement the intercept method returning next.handle() to pass control to the next handler.
3
Add timing and response modification logic in interceptor
Inside the intercept method of LoggingInterceptor, record the current time before calling next.handle(). Use pipe with map from rxjs/operators to calculate elapsed time after the handler completes. Log the elapsed time with console.log. Modify the response by appending ' - Processed by interceptor' to the original data.
NestJS
Hint
Use Date.now() to get current time, then use pipe and map to modify the response and log elapsed time.
4
Apply the interceptor to the controller route
Import UseInterceptors from @nestjs/common. Add the decorator @UseInterceptors(LoggingInterceptor) above the getHello method in AppController to apply the interceptor to that route.
NestJS
Hint
Use the @UseInterceptors(LoggingInterceptor) decorator above the getHello method.
Practice
(1/5)
1. What is the main reason to use interceptors in NestJS? Interceptors help to add logic that applies to many parts of the app without repeating code. Why is this useful?
easy
A. They add shared logic before and after main code, like logging or timing.
B. They replace controllers to handle HTTP requests directly.
C. They store data permanently in the database.
D. They generate frontend UI components automatically.
Solution
Step 1: Understand the role of interceptors
Interceptors run code before and after the main handler, allowing shared tasks like logging or error handling.
Step 2: Compare with other options
Controllers handle requests, databases store data, and UI components are unrelated to interceptors.
Final Answer:
They add shared logic before and after main code, like logging or timing. -> Option A
Quick Check:
Interceptors add shared logic = A [OK]
Hint: Interceptors wrap main code to add shared tasks [OK]
B. The console.log statement is after next.handle(), so it never runs.
C. The class is missing the @Controller() decorator.
D. The intercept method does not return the observable from next.handle().
Solution
Step 1: Check the intercept method return
The intercept method must return the observable from next.handle() to continue the request flow.
Step 2: Identify missing return
Here, next.handle() is called but its result is not returned, so the request does not proceed and logs may not appear.
Final Answer:
The intercept method does not return the observable from next.handle(). -> Option D
Quick Check:
Missing return next.handle() = D [OK]
Hint: Always return next.handle() observable in intercept() [OK]
Common Mistakes:
Forgetting to return next.handle()
Misplacing console.log after next.handle()
Confusing decorators for interceptors
5. You want to measure the time taken by any request handler in your NestJS app. Which interceptor approach correctly adds this cross-cutting timing logic?