#Setup HttpModule Interceptor in Nestjs

9 messages · Page 1 of 1 (latest)

unique trail
#

In my application Im calling third parts APIs via HttpService with axios, I want to implement a interceptor where that I can log all the request urls that passing trough the httpService.

import { HttpModule as AxiosHttpModule, HttpService } from '@nestjs/axios';
import { Global, Module, OnModuleInit } from '@nestjs/common';
import { AxiosError, AxiosResponse } from 'axios';

@Global()
@Module({
  imports: [AxiosHttpModule],
  exports: [AxiosHttpModule],
})
export class HttpModule extends AxiosHttpModule implements OnModuleInit {
  constructor(private readonly httpService: HttpService) {
    super();
  }

  public onModuleInit(): any {
    const axios = this.httpService.axiosRef;

    axios.interceptors.request.use(
      (config) => {
        console.log(`Request URL: ${config.url}`);
        console.log(`Request Method: ${config.method}`);
        return config;
      },
      (error: AxiosError) => {
        console.error('Request Error:', error);
        return Promise.reject(error);
      },
    );

    axios.interceptors.response.use(
      (response: AxiosResponse) => {
        console.log('Response:', response.data);
        return response;
      },
      (error: AxiosError) => {
        console.error('Response Error:', error.response?.data);
        return Promise.reject(error);
      },
    );
  }
}

And I imported it in appmodule

HttpModule.registerAsync({
      useFactory: (configService: ConfigService) => {
        return {
          timeout: 20000,
          baseURL: configService.getOrThrow('BASE_URL'),
          headers: {
            'Content-Type': 'application/json',
          },
        };
      },
      inject: [ConfigService],
      global: true,
    }),

But the request logging is not working, I cannot figure out why.

Any help would be greatly appreciated.

sinful river
#

you could use a middleware to check the protocol being used

chilly vortex
#

@unique trail I think your mistake is extending the original module.

#

Use a normal wrapper module that imports HttpModule (the original one) and registers it using config service

#

The rest would look largely the same

#

The problem with this solition is that you import AxiosHttpModule and re-export it completely unconfigured.