Response transformation changes the data before sending it to the user. It helps make the output clear and safe.
Response transformation in NestJS
Introduction
Syntax
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable() export class TransformInterceptor<T> implements NestInterceptor<T, any> { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe( map(data => { // transform data here const transformedData = data; // example placeholder return transformedData; }), ); } }
The interceptor uses RxJS map to change the response data.
Always return the transformed data inside the map function.
Examples
success flag.NestJS
map(data => ({ success: true, data }))password field from the response data.NestJS
map(data => { delete data.password; return data; })
id and name.NestJS
map(data => data.map(item => ({ id: item.id, name: item.name })))
Sample Program
This example shows a controller that returns user data. The interceptor removes the password before sending the response.
NestJS
import { Controller, Get, UseInterceptors, Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; @Injectable() class TransformInterceptor implements NestInterceptor { intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe( map(data => { // Remove password before sending response const { password, ...safeData } = data; return safeData; }), ); } } @Controller('users') @UseInterceptors(TransformInterceptor) export class UserController { @Get() getUser() { return { id: 1, username: 'alice', password: 'secret123' }; } }
Important Notes
Interceptors run after the controller returns data but before it reaches the client.
Use response transformation to keep sensitive data safe and output clean.
Summary
Response transformation changes data before sending it to users.
Use interceptors with RxJS map to modify responses.
It helps hide sensitive info and keep API responses consistent.
Practice
1. What is the main purpose of response transformation in NestJS?
easy
Solution
Step 1: Understand response transformation concept
Response transformation means changing the data before it is sent to the user.Step 2: Identify the correct purpose in NestJS context
In NestJS, response transformation is used to modify or format the response data.Final Answer:
To modify data before sending it to the client -> Option AQuick Check:
Response transformation = modify data before sending [OK]
Hint: Response transformation changes output data before sending [OK]
Common Mistakes:
- Confusing response transformation with authentication
- Thinking it manages database connections
- Assuming it logs errors
2. Which of the following is the correct way to apply a response transformation interceptor in NestJS?
easy
Solution
Step 1: Recall NestJS interceptor usage
Interceptors are applied using the @UseInterceptors decorator on controllers or methods.Step 2: Match correct syntax
The correct syntax is @UseInterceptors(new InterceptorClass()).Final Answer:
@UseInterceptors(new TransformInterceptor()) -> Option BQuick Check:
Use @UseInterceptors with new instance [OK]
Hint: Use @UseInterceptors with new interceptor instance [OK]
Common Mistakes:
- Using @Injectable instead of @UseInterceptors
- Calling interceptor as a method on controller
- Trying to use app.use for interceptors
3. Given this interceptor code snippet, what will be the transformed response?
intercept(context, next) {
return next.handle().pipe(map(data => ({ result: data })));
}medium
Solution
Step 1: Understand the interceptor's map function
The map operator wraps the original data inside an object with key 'result'.Step 2: Predict the transformed output
The response will be an object: { result: originalData }.Final Answer:
{ result: originalData } -> Option CQuick Check:
map wraps data in { result: ... } [OK]
Hint: map operator wraps data in new object key [OK]
Common Mistakes:
- Assuming original data is unchanged
- Confusing key name as 'data' instead of 'result'
- Expecting an error from this code
4. What is wrong with this interceptor code that tries to transform the response?
intercept(context, next) {
next.handle().pipe(map(data => data.trim()));
}medium
Solution
Step 1: Check interceptor return value
Interceptors must return the observable from next.handle().pipe(...).Step 2: Identify missing return
The code calls next.handle().pipe(...) but does not return it, so the response is undefined.Final Answer:
Missing return statement for the observable -> Option DQuick Check:
Always return next.handle().pipe(...) [OK]
Hint: Always return the observable from intercept method [OK]
Common Mistakes:
- Forgetting to return the observable
- Assuming map cannot be used in intercept
- Misusing trim() on non-string data
5. You want to hide the user's password field from all API responses using response transformation. Which approach is best in NestJS?
hard
Solution
Step 1: Understand response transformation goal
We want to remove sensitive info from outgoing responses, not database or requests.Step 2: Choose best NestJS method
Interceptors can transform responses globally, ideal for removing password fields before sending.Step 3: Evaluate other options
Modifying DB schema or middleware won't affect response data; setting password null in controllers is repetitive.Final Answer:
Create an interceptor that maps the response and deletes the password field -> Option AQuick Check:
Use interceptor to hide sensitive response data [OK]
Hint: Use interceptor to remove sensitive fields from responses [OK]
Common Mistakes:
- Trying to filter password in middleware (affects requests)
- Changing database schema instead of response
- Manually nulling password in every controller
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
