0
0
NestJSframework~5 mins

Response transformation in NestJS

Choose your learning style9 modes available
Introduction

Response transformation changes the data before sending it to the user. It helps make the output clear and safe.

You want to hide sensitive information like passwords before sending data.
You need to change the format of data to match what the user expects.
You want to add extra information or remove unnecessary details from the response.
You want to keep your API responses consistent across different endpoints.
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
This wraps the original data inside an object with a success flag.
NestJS
map(data => ({ success: true, data }))
This removes the password field from the response data.
NestJS
map(data => {
  delete data.password;
  return data;
})
This transforms an array of items to only include 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'
    };
  }
}
OutputSuccess
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.