I need to get the request body on my interceptor, before it goes to my controller:
import { Injectable, NestInterceptor, ExecutionContext, HttpException, HttpStatus } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class ExcludeNullInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, call$: Observable<any>): Observable<any> {
// How can I get the request body here?
// Need to be BEFORE the Controller exec
}
}
A NestJS Interceptor is basically a class annotated with the @Injectable () decorator. If you wish to know more about @Injectable () decorator, please refer to the detailed post on NestJS Providers. However, apart from the decorator, an interceptor should also implement the NestInterceptor interface.
To get the body values from the POST method request, you can use the @Body () decorator function from the @nestjs/common module in Nestjs.
We can bind interceptors on various levels such as method, controller or even global. To bind an interceptor, we use the @UseInterceptor () decorator. Basically, the LoggingInterceptor will be applicable to this route handler in the controller. If you wish to know more about controllers, refer to the detailed post about NestJS Controllers.
We need to tell NestJS to parse the specified routes with the raw body parser. Then parse every other route with the regular JSON parser. Then you can add any middleware you like after that. Now in the controller for handling the specified route we can access the parsedRawBody parameter.
In your interceptor you can do:
async intercept(context: ExecutionContext, stream$: Observable<any>): Observable<any> {
const body = context.switchToHttp().getRequest().body;
// e.g. throw an exception if property is missing
Alternatively, you can use middleware where you directly have access to the request:
(req, res, next) => {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With