An interceptor is a class annotated with @Injectable() that implements the NestInterceptor interface. It must implement the intercept() method, which receives the ExecutionContext (providing details about the current request/process) and a CallHandler.
To allow the route handler to execute, you must call next.handle(). Because handle() returns an RxJS Observable, you can use RxJS operators to execute logic both before and after the route handler runs.
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';
@Injectable()
export class LoggingInterceptor implements NestInterceptor {
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
console.log('Before...');
const now = Date.now();
return next
.handle()
.pipe(
tap(() => console.log(`After... ${Date.now() - now}ms`)),
);
}
}