Lädt...

🔧 Enhancing API Responses with a Global Response Interceptor in NestJS


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

In a modern API-driven application, maintaining a consistent response format is crucial for better client-side handling and debugging. NestJS provides a powerful mechanism called Interceptors, which allows us to modify and enhance response structures globally or at the controller level.

What is an Interceptor in NestJS?

Interceptors in NestJS sit between the request and response cycle, allowing us to:

  • Modify the response before sending it to the client.
  • Handle logging, transformation, or caching.
  • Implement custom logic like timing requests or modifying headers.

The @Injectable() decorator marks an interceptor as a service that can be used globally or within specific controllers.

Creating a Global Response Interceptor

Let's analyze the following ResponseInterceptor implementation:

import {
  CallHandler,
  ExecutionContext,
  Injectable,
  NestInterceptor,
} from '@nestjs/common';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

export interface ApiResponse<T> {
  data: T;
  message?: string;
}

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<ApiResponse<T>> {
  intercept(
    context: ExecutionContext,
    next: CallHandler<ApiResponse<T>>,
  ): Observable<{ success: true; data: T; message: string }> {
    return next.handle().pipe(
      map((data) => {
        return {
          success: true,
          message: data?.message ?? 'Request successful',
          data: data?.data ?? (data as T),
        };
      }),
    );
  }
}

Applying the ResponseInterceptor Globally

To apply this interceptor to all responses, register it in the main.ts file:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ResponseInterceptor } from './interceptors/response.interceptor';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // Apply globally
  app.useGlobalInterceptors(new ResponseInterceptor());

  await app.listen(3000);
}
bootstrap();

Using the Interceptor in Specific Controllers

If you want to use the ResponseInterceptor only for certain controllers instead of globally, apply it at the controller level:

import { Controller, Get, UseInterceptors } from '@nestjs/common';
import { ResponseInterceptor } from './interceptors/response.interceptor';

@Controller('users')
@UseInterceptors(ResponseInterceptor)
export class UserController {
  @Get()
  getUsers() {
    return { data: [{ id: 1, name: 'John Doe' }], message: 'Users fetched' };
  }
}

Benefits of Using a Response Interceptor

✅ Consistent API responses across all endpoints.
✅ Reduces boilerplate – No need to manually structure responses in every controller.
✅ Improves maintainability – Easy to update response format centrally.
✅ Enhances API documentation by enforcing a structured format.

Regards,
N I Rimon

...

🔧 Enhancing API Responses with a Global Response Interceptor in NestJS


📈 77.51 Punkte
🔧 Programmierung

🔧 Simplifying API responses in Laravel with kolirt/laravel-api-response package


📈 31.39 Punkte
🔧 Programmierung

🔧 Enhancing API Workflows: A Comprehensive Guide to Mock Responses and Efficient Testing


📈 28.44 Punkte
🔧 Programmierung

🔧 How To Keep Track Of Responses In NestJS


📈 27.01 Punkte
🔧 Programmierung

🔧 Exploring Custom Decorators in NestJS: Enhancing Your API with Metadata and Reusability


📈 26.85 Punkte
🔧 Programmierung

🔧 EchoAPI Interceptor: Making API Capture and Debugging Fun and Effortless


📈 26.65 Punkte
🔧 Programmierung

🔧 EchoAPI Interceptor: Making API Capture and Debugging Fun and Effortless


📈 26.65 Punkte
🔧 Programmierung

🔧 🚦 Rate Limiting in NestJS Using @nestjs/throttler


📈 25.42 Punkte
🔧 Programmierung

🔧 NestJS Fundamentals Part 1: Modularity in NestJS


📈 25.42 Punkte
🔧 Programmierung

🔧 Integrating Firebase Authentication into NestJS with nestjs-firebase-auth


📈 25.42 Punkte
🔧 Programmierung

🔧 Fix long import paths in your NestJS project #nestjs


📈 25.42 Punkte
🔧 Programmierung

🔧 Discover the magic of custom decorators in NestJS #nestjs


📈 25.42 Punkte
🔧 Programmierung

🔧 Website for NestJS-Mod - https://nestjs-mod.com


📈 25.42 Punkte
🔧 Programmierung

🔧 How to Implement Data Validation in NestJS Using nestjs-joi and joi-class-decorators


📈 25.42 Punkte
🔧 Programmierung

🔧 NestJS tip: how to use Node.js built-in .env file reader with NestJS CLI


📈 25.42 Punkte
🔧 Programmierung

🔧 Queuing jobs in NestJS using @nestjs/bullmq package


📈 25.42 Punkte
🔧 Programmierung

🔧 Iterative Thought Refiner: Enhancing LLM Responses via Dynamic Adaptive Reasoning


📈 23.76 Punkte
🔧 Programmierung

🔧 StructuredRAG: Enhancing LLM JSON Responses with Hierarchical Organization and Type Annotations


📈 23.76 Punkte
🔧 Programmierung

🔧 Enhancing Error Logging in NestJS with a Custom Sentry Logger


📈 22.17 Punkte
🔧 Programmierung

🔧 Enhancing NestJS Development: Improving Module Management Efficiency


📈 22.17 Punkte
🔧 Programmierung

🔧 🚀Secure API-to-API Communication with HMAC: Implementation using NestJS, AWS, and Postman🔥


📈 22.07 Punkte
🔧 Programmierung

🔧 Angular - Faire un Interceptor pour vos requêtes HTTP.


📈 21.97 Punkte
🔧 Programmierung

🔧 Dominando o HTTP Interceptor do Angular para Gestão de Autorização de APIs


📈 21.97 Punkte
🔧 Programmierung

🔧 Angular Interceptor


📈 21.97 Punkte
🔧 Programmierung

📰 No Man's Sky: Interceptor-Update bringt neue Schiffe und Welten


📈 21.97 Punkte
📰 IT Security Nachrichten

🔧 🌐 Golang gRPC with Auth Interceptor, Streaming and Gateway in Practice 🐹


📈 21.97 Punkte
🔧 Programmierung

🐧 No Man's Sky gets another huge update with Interceptor


📈 21.97 Punkte
🐧 Linux Tipps

🔧 🌐 Golang gRPC with Auth Interceptor, Streaming and Gateway in Practice 🐹


📈 21.97 Punkte
🔧 Programmierung

🪟 No Man’s Sky: Interceptor Update brings corruption to the galaxy


📈 21.97 Punkte
🪟 Windows Tipps

🔧 Creating Axios Interceptor in React and NextJs


📈 21.97 Punkte
🔧 Programmierung

matomo