Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios interceptors with Typescript

How to correctly use axios's inteceptors with typescript:

import axios, { AxiosRequestConfig, AxiosInstance } from 'axios'

HTTP.interceptors.request.use((config: AxiosRequestConfig) => config)

For example, when i create axios instance, i set up default config:

const conf: AxiosRequestConfig = {
  baseURL: process.env.VUE_APP_API_URL
}

const HTTP: AxiosInstance = axios.create(conf)

But when i try to use interceptor with custom headers:

HTTP.interceptors.request.use((config: AxiosRequestConfig) =>{
  headers: {
    'x-projectkey': 1234
  }
})

It doesn't work:

Argument of type '(config: AxiosRequestConfig) => void' is not assignable to parameter of type '(value: AxiosRequestConfig) => AxiosRequestConfig | Promise<AxiosRequestConfig>'

I'm still new to TS, can't figure this out.

like image 508
Alexander Kim Avatar asked Oct 20 '25 16:10

Alexander Kim


1 Answers

Go to the type definition of AxiosRequestConfig, you can see that, everything, including axios headers is optional:

interface AxiosRequestConfig<D = any> {
  url?: string;
  method?: Method | string;
  baseURL?: string;
  timeout?: number;
  timeoutErrorMessage?: string;
  withCredentials?: boolean;
  // ... omited 
}

When creating an axiosInstance and adding config, the config should be returned for the instance to pick up the configuration:

const axiosInstance = axios.create();

axiosInstance.interceptors.request.use((config) => {
  if (config.headers) { // <- adding a check 
    config.headers["x-projectkey"] = 1234; // no errors
  }
  config.withCredentials = true; // to include credential, it should be outside of "if" block 
  return config;
});

Then in every request you made with the axiosInstance, it will include the x-projectkey header and credentials:

axiosInstance.get("url");
like image 167
Enfield Li Avatar answered Oct 22 '25 08:10

Enfield Li



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!