🦅 NestJS Intermediate

What is the NestJS interceptor for response transformation?

Answer

A common pattern is using an interceptor to wrap all API responses in a standard envelope. Create an interceptor implementing NestInterceptor: intercept(context: ExecutionContext, next: CallHandler): Observable<any> { return next.handle().pipe(map(data => ({ success: true, data }))); }. This transforms { name: 'Alice' } into { success: true, data: { name: 'Alice' } } for all endpoints. Apply globally: app.useGlobalInterceptors(new TransformInterceptor()). Another common use is a logging interceptor that records execution time: tap(() => console.log(\`Executed in \${Date.now() - now}ms\`)). Interceptors use RxJS operators so you have full streaming capabilities for timeouts, retries, and error handling.