How to Enhance Request Data with Meta Data using Axios 1.4.0 Interceptors

Looking to enhance a request by including metadata using an interceptor, but facing issues with the code snippets I've come across:

instance.interceptors.request.use(
    function (config) {
        config.metadata = { startTime: new Date() };
        return config;
    },
    function (error) {
        return Promise.reject(error);
    }
);

Encountering the following error:

Property 'metadata' does not exist on type 'InternalAxiosRequestConfig'

https://i.sstatic.net/LB2LV.png

My environment includes Axios 1.4.0 and Typescript 5.0.4. Any insights on what might be causing this issue? šŸ¤”

Answer ā„–1

If you want to customize your Axios configuration and utilize interceptors, here's a method to measure request duration:

import { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios';

import { getBenchmarkMiliseconds } from 'someBenchmarkingLib';


interface AxiosRequestConfigWithMetadata<T = unknown> extends InternalAxiosRequestConfig<T> {
  metadata?: {
    startTime?: number;
    endTime?: number;
  };
}

interface AxiosResponseWithMetadata<T = unknown, D = unknown> extends AxiosResponse<T, D> {
  config: AxiosRequestConfigWithMetadata<D>;
}
interface AxiosErrorWithMetadata<T = unknown, D = unknown> extends AxiosError<T, D> {
  config: AxiosRequestConfigWithMetadata<D>;
}

export interface AxiosInterceptorProps {
  axiosClient: AxiosInstance;
}

export const addLoggingInterceptors = (props: AxiosInterceptorProps) => {
  props.axiosClient.interceptors.request.use(
    (requestConfig: AxiosRequestConfigWithMetadata) => {
      requestConfig.metadata = requestConfig.metadata || {};
      requestConfig.metadata.startTime = getBenchmarkMiliseconds();
      return requestConfig;
    },
    (error) => {
      return Promise.reject(error);
    },
  );

  props.axiosClient.interceptors.response.use(
    (response: AxiosResponseWithMetadata) => {
      const startTime = response.config.metadata?.startTime;
      // do something here
      return response;
    },
    (error: AxiosErrorWithMetadata) => {
      const startTime = error?.config?.metadata?.startTime;
      // do something here
      return Promise.reject(error);
    },
  );
};


Edit 1: If you are using later versions of axios (e.g., axios=1.7.2), you may need to adjust the type like this:

interface AxiosRequestConfigWithMetadata<T = unknown> extends AxiosRequestConfig<T> {
  headers: AxiosRequestHeaders;
  metadata?: {
    startTime?: number;
    endTime?: number;
  };
}

Answer ā„–2

There has been a recent change in the return type. I am uncertain about the recommended approach currently, but one possible solution is to extend it using the typescript declaration merging feature

declare module 'axios' {
  export interface InternalAxiosRequestConfig {
    meta: any;
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is preventing the dependency injection of AuthHttp (angular2-jwt) into a component?

UPDATE: Success! Problem Solved After much trial and error, I finally discovered the solution to my issue. It turned out that the problem lied in a simple configuration mistake. To rectify this, I made changes to both my package.json (dependencies section ...

Ways to enhance the Date class

While working on my Angular2 application, I noticed that all the dates returned by my controller are in the format "2017-02-2700:00:00". I wanted to customize the way Date objects are created so that I can remove the T from the string while still maintaini ...

The RazorPay callback encountered an Uncaught TypeError indicating that the function is not recognized

In my TypeScript class, I have a defined handler as follows: "handler": function (response) { this.sendUserStatus(); }, Unfortunately, when I attempt to call this.sendUserStatus();, I encounter the following error: Uncaught Typ ...

What is the best way to invert the values of a string array?

Imagine having the following array : fruits: string[] = ['banana', 'strawberry', 'kiwi', 'apple']; Is there a way to transform it into : fruits = ['ananab', 'yrrebwarts', 'iwki', &apo ...

'The instantiation of 'TSearchInput' may involve a type that is completely different from that of 'RotatingItemSearchInput'

I am encountering an issue where I want each record in the object to have different value types, but I keep running into these errors: 1 - 'TSearchInput' could potentially be instantiated with a type that is not related to 'RotatingItemSear ...

Discover a Simple Trick to Enhance tsc Output: Unveil the Art of

When I work on a TypeScript project, I typically use the watch mode of the compiler: tsc --watch However, one issue I face is that it's challenging to identify errors in the output since they are displayed as plain text: Sometimes I don't even ...

Using the Ngclass function with a pair of objects

Can you include 2 objects in an ngclass function like this? <div class="progress-bar"[ngClass]="getProgressValues(obj.val1,obj.val2)"> </div> I am encountering a JSON error. SyntaxError: JSON.parse: bad control character in string literal at l ...

Sort columns in a MUI datatable

I am facing an issue with sorting in a column that represents an object. Although I can display the desired value, the sorting functionality does not seem to work for that particular column. Here is an example to provide better clarity: const [data, set ...

What is the reason for the lack of functionality of the "unique" field when creating a schema?

I've created a schema where the username field should be unique, but I'm having trouble getting it to work (The "required" constraint is functioning correctly). I've tried restarting MongoDB and dropping the database. Any idea what I might b ...

Top Tips in Angular2 for showing buttons depending on a user's security authorizations

Iā€™m in the process of building my inaugural Angular 2 website. Featuring a Bootstrap NavBar positioned on the left side, users can effortlessly navigate to various pages within the site. The navigation buttons displayed on the NavBar are tailored based o ...

TS2339: The type does not have a property called "assign"

I have a file that contains fixed data under the name QRCategories and I need to transmit this data as an observable. The service responsible for sending this data is: public qrCodeCategoriesList(): Observable<QRCategoryListResponse> { return o ...

Obtain the union type by extracting values from an indexed object

Suppose there is an indexed type: type X = { a: 'A', b: 'B' } Is there a way to derive the following type from it: type V = 'A' | 'B' without using an explicit method like this: type V = X['a'] | X[& ...

Zod offers the flexibility to customize validation for optional keys

Currently, I am exploring the utility of using zod within my application. I am facing a minor issue when attempting to parse an object that may contain optional keys. While using .passthrough allows the keys to remain in the object, I am interested in cu ...

Global error handling in Nest.js: A guide to applying consistent error logic throughout your application

Nest.js I successfully implemented error handling logic as required by the project. Is there a way to reuse this logic for multiple routes in a controller without duplicating the code? @Controller() export class AppController { constructor(private read ...

Discover the process of implementing Firebase Authentication in Deno Fresh!

I've been trying to set up authentication in Fresh using the official Firebase documentation, https://firebase.google.com/docs/auth but I can't seem to get it to work. Does anyone know of any other resources like docs, articles, or blogs that co ...

The TSC directive requiring 372 seconds for execution

I recently discovered that my TypeScript Firebase repository, used for cloud functions and consisting of only 6 files in the src directory, was taking an unusually long time to compile when running the tsc command. To investigate further, I executed it wit ...

Is there a TypeScript equivalent to NSUserDefaults or SharedPreferences?

Just getting started with Angularjs-2.3 TypeScript and I have a specific scenario where I need to save the userId in the app so it can be accessed anywhere within the app. If I were developing for Android or iOS, I would typically use NSUserDefaults and S ...

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

When the key property is utilized, the state in react useState is automatically updated; however, for updating without it, the useEffect or a

I am working on a component that looks like this: import React, { useState } from "react"; import { FormControl, TextField } from "@material-ui/core"; interface IProps { text?: string; id: number; onValueChange: (text: stri ...

What is the best way to display a loading state while waiting for all Firebase data requests to be fully processed?

Hey there! I'm looking for some advice on how to display a loading indicator like this: https://i.sstatic.net/7luvR.gif while waiting for my Firebase data to load completely. I attempted to use <div *ngIf="!listOfFoodObject"> <img [src ...