0
0
NestJSframework~30 mins

Interceptor interface in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating a Logging Interceptor with NestJS Interceptor Interface
📖 Scenario: You are building a NestJS backend application. You want to log every incoming request and outgoing response to help with debugging and monitoring.
🎯 Goal: Create a simple logging interceptor using the NestJS Interceptor interface that logs the request method and URL before the request is handled, and logs the response data after the request is processed.
📋 What You'll Learn
Create a class called LoggingInterceptor that implements the NestInterceptor interface
Add a intercept method with parameters context and next
Inside intercept, log the HTTP method and URL from the request
Use next.handle() to continue the request processing
Use tap operator from rxjs to log the response data
Export the LoggingInterceptor class
💡 Why This Matters
🌍 Real World
Logging interceptors help developers monitor API usage and debug issues by tracking requests and responses in real time.
💼 Career
Understanding interceptors is essential for backend developers working with NestJS to implement cross-cutting concerns like logging, caching, and authentication.
Progress0 / 4 steps
1
Import required modules and create LoggingInterceptor class
Import Injectable, NestInterceptor, ExecutionContext, and CallHandler from @nestjs/common. Also import Observable from rxjs. Create an exported class called LoggingInterceptor that implements NestInterceptor.
NestJS
Need a hint?

Start by importing the necessary NestJS interfaces and create the class with the correct name and interface.

2
Extract HTTP request method and URL from ExecutionContext
Inside the intercept method, create a constant called request by calling context.switchToHttp().getRequest(). Then create constants method and url from request.method and request.url respectively.
NestJS
Need a hint?

Use context.switchToHttp().getRequest() to get the HTTP request object, then get method and url from it.

3
Log request info and use next.handle() with tap to log response
Inside intercept, log the string `Incoming Request: ${method} ${url}` using console.log. Then return next.handle() piped with tap from rxjs/operators that logs `Response: ${JSON.stringify(data)}` where data is the response.
NestJS
Need a hint?

Use console.log to log the request info. Use next.handle().pipe(tap(...)) to log the response data.

4
Add @Injectable decorator and export the class
Make sure the LoggingInterceptor class is decorated with @Injectable() and is exported. This completes the interceptor implementation.
NestJS
Need a hint?

Check that @Injectable() is above the class and the class is exported.