Bird
Raised Fist0
NestJSframework~10 mins

Response transformation in NestJS - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Response transformation
Incoming HTTP Request
↓
Controller Method Called
↓
Return Raw Data Object
↓
Interceptor Intercepts Response
↓
Transform Data (e.g., format, filter)
↓
Send Transformed Response to Client
The request hits the controller, which returns data. The interceptor catches this data, transforms it, then sends the modified response to the client.
Execution Sample
NestJS
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler) {
    return next.handle().pipe(map(data => ({ data })));
  }
}
This interceptor wraps the original response data inside an object with a 'data' key.
Execution Table
StepActionInput DataTransformationOutput Data
1Controller returns raw data{ id: 1, name: 'Alice' }None yet{ id: 1, name: 'Alice' }
2Interceptor intercepts response{ id: 1, name: 'Alice' }Wrap in { data: ... }{ data: { id: 1, name: 'Alice' } }
3Send response to client{ data: { id: 1, name: 'Alice' } }None{ data: { id: 1, name: 'Alice' } }
💡 Response sent after transformation wrapping original data in a 'data' object.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
responseDataundefined{ id: 1, name: 'Alice' }{ data: { id: 1, name: 'Alice' } }{ data: { id: 1, name: 'Alice' } }
Key Moments - 2 Insights
Why does the interceptor wrap the data inside another object?
Because the interceptor modifies the response by wrapping it in a 'data' key as shown in step 2 of the execution_table, so the client always receives a consistent response shape.
Does the controller need to know about the transformation?
No, the controller just returns raw data. The interceptor handles transformation separately, as seen in step 1 vs step 2 in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output data after step 2?
A{ data: { id: 1, name: 'Alice' } }
B{ id: 1, name: 'Alice' }
Cundefined
Dnull
💡 Hint
Check the 'Output Data' column in row for step 2 in execution_table.
At which step does the response get transformed?
AStep 1
BStep 2
CStep 3
DNo transformation occurs
💡 Hint
Look at the 'Transformation' column in execution_table rows.
If the interceptor did not wrap data, what would the final response be?
A{ data: { id: 1, name: 'Alice' } }
Bnull
C{ id: 1, name: 'Alice' }
DAn error
💡 Hint
Compare 'Output Data' in step 1 and step 2 in execution_table.
Concept Snapshot
NestJS Response Transformation:
- Use an interceptor to catch controller responses.
- Modify or wrap data inside intercept() method.
- Return transformed data via next.handle().pipe(map(...)).
- Keeps controller code clean and consistent response format.
- Useful for adding metadata or filtering sensitive info.
Full Transcript
In NestJS, response transformation happens by using an interceptor. When a request comes in, the controller returns raw data. The interceptor catches this data before it goes to the client. It then changes the data, for example by wrapping it inside an object with a 'data' key. Finally, the transformed response is sent to the client. This keeps the controller simple and lets you control response format in one place.

Practice

(1/5)
1. What is the main purpose of response transformation in NestJS?
easy
A. To modify data before sending it to the client
B. To handle database connections
C. To manage user authentication
D. To log server errors

Solution

  1. Step 1: Understand response transformation concept

    Response transformation means changing the data before it is sent to the user.
  2. Step 2: Identify the correct purpose in NestJS context

    In NestJS, response transformation is used to modify or format the response data.
  3. Final Answer:

    To modify data before sending it to the client -> Option A
  4. Quick 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
A. controller.transform(TransformInterceptor)
B. @UseInterceptors(new TransformInterceptor())
C. app.use(TransformInterceptor)
D. @Injectable(TransformInterceptor)

Solution

  1. Step 1: Recall NestJS interceptor usage

    Interceptors are applied using the @UseInterceptors decorator on controllers or methods.
  2. Step 2: Match correct syntax

    The correct syntax is @UseInterceptors(new InterceptorClass()).
  3. Final Answer:

    @UseInterceptors(new TransformInterceptor()) -> Option B
  4. Quick 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
A. { data: originalData }
B. originalData
C. { result: originalData }
D. An error will occur

Solution

  1. Step 1: Understand the interceptor's map function

    The map operator wraps the original data inside an object with key 'result'.
  2. Step 2: Predict the transformed output

    The response will be an object: { result: originalData }.
  3. Final Answer:

    { result: originalData } -> Option C
  4. Quick 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
A. next.handle() should not be called
B. map operator cannot be used inside intercept
C. trim() is not a valid method on data
D. Missing return statement for the observable

Solution

  1. Step 1: Check interceptor return value

    Interceptors must return the observable from next.handle().pipe(...).
  2. Step 2: Identify missing return

    The code calls next.handle().pipe(...) but does not return it, so the response is undefined.
  3. Final Answer:

    Missing return statement for the observable -> Option D
  4. Quick 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
A. Create an interceptor that maps the response and deletes the password field
B. Modify the database schema to exclude password
C. Use a middleware to filter out password from requests
D. Send password as null in the controller methods

Solution

  1. Step 1: Understand response transformation goal

    We want to remove sensitive info from outgoing responses, not database or requests.
  2. Step 2: Choose best NestJS method

    Interceptors can transform responses globally, ideal for removing password fields before sending.
  3. Step 3: Evaluate other options

    Modifying DB schema or middleware won't affect response data; setting password null in controllers is repetitive.
  4. Final Answer:

    Create an interceptor that maps the response and deletes the password field -> Option A
  5. Quick 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 strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard