reactjstypescriptaxiosinterceptor

Axios Interceptor to customize header for uuid


import axios, { AxiosInstance } from "axios";
import { v4 as uuidv4 } from 'uuid';


const axiosInstance: AxiosInstance = axios.create({
  baseURL: "http://localhost:8080",
  timeout: 10000, // 10 s
  headers: {
    "Content-Type": "application/json",
  },
});

axiosInstance.interceptors.request.use(config => {
  // Generate a unique correlation ID
  const correlationId = uuidv4();
  
  // Attach the correlation ID to the headers
  if (config.headers) {
    config.headers['X-Correlation-ID'] = correlationId;
  } else {
    config.headers = {
      'corRelationId': correlationId,
    };
  }

  return config;
}, error => {
  return Promise.reject(error);
});

export default axiosInstance;

I'm trying to create corRelationId dynamically send every request but i'm getting error

Error TS2322: Type '{ corRelationId: string; }' is not assignable to type 'AxiosRequestHeaders'. Type '{ corRelationId: string; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more. 19 | config.headers['X-Correlation-ID'] = correlationId; 20 | } else {

21 | config.headers = { | ^^^^^^^^^^^^^^ 22 | 'corRelationId': correlationId, 23 | }; 24 | }


Solution

  • AxiosRequestHeaders isn't a plain object which is why TypeScript is complaining. See https://github.com/axios/axios?tab=readme-ov-file#-axiosheaders

    It's also never optional so there's no need for your check...

    interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> {
      headers: AxiosRequestHeaders; // 👈 not optional
    }
    

    Simply set the header key / value pair that you want. You should also use the set() method as direct property access is deprecated

    // Don't blanket-set content-type headers
    const axiosInstance: AxiosInstance = axios.create({
      baseURL: 'http://localhost:8080',
      timeout: 10000, // 10 s
    });
    
    axiosInstance.interceptors.request.use((config) => {
      const correlationId = uuidv4();
    
      config.headers.set('X-Correlation-ID', correlationId);
      return config;
    }, null, { synchronous: true });
    

    Some notes: