Interceptors in Nest JS | Arshnoor Singh

Interceptors in Nest JS

Interceptor in nest is an interceptor is a class annotated with the @Injectable() decorator and implements the NestInterceptor interface.

Interceptors have a set of useful capabilities

  • bind extra logic before / after method execution
  • transform the result returned from a function
  • transform the exception thrown from a function
  • extend the basic function behavior
  • completely override a function depending on specific conditions specifically for caching.

Each interceptor implements the intercept() method, which takes two arguments. The first one is the ExecutionContext instance. The ExecutionContext inherits from ArgumentsHost.

Execution context

By extending ArgumentsHost, ExecutionContext also adds several new helper methods that provide additional details about the current execution process.

These details can be helpful in building more generic interceptors that can work across a broad set of controllers, methods, and execution contexts.

Call handler

The second argument is a CallHandler. The CallHandler interface implements the handle() method, which you can use to invoke the route handler method at some point in your interceptor.

This approach means that the intercept() method effectively wraps the request/response stream.

As a result, we may implement custom logic both before and after the execution of the final route handler.

Using Aspect Oriented Programming terminology, the invocation of the route handler (i.e. calling handle()) is called a Pointcut, indicating that it's the point at which our additional logic is inserted.

Aspect interception

The first use case we'll look at is to use an interceptor to log user interaction such as storing user calls, asynchronously dispatching events or calculating a timestamp.

Since handle() returns an RxJS Observable, we have a wide choice of operators we can use to manipulate the stream.

Binding interceptors

In order to set up the interceptor, we use the @UseInterceptors() decorator imported from the @nestjs/common package. Like pipes and guards, interceptors can be controller-scoped, method-scoped, or global-scoped.