typescriptaxios

How to fix config.headers.Authorization "Object is possibly undefined" when using axios interceptors


I got the following code :

loggedInAxios.interceptors.request.use(
  async (config) => {
    if (isTokenExpired('access_token')) {
      const response = await getRefreshToken();
      await refreshAccessToken(response);
    }
    const accessToken = localStorage.getItem('access_token');
    config.headers.Authorization = `Bearer ${accessToken}`;
    return config;
  },
  (error) => error
);

But typescript is complaining that config.headers.Authorization object is possibly undefined.

I found a way by adding the following:

if (!config) {
 config = {};
}
if (!config.headers) {
  config.headers = {};
}

But I do not think that this is the best way to do it...


Solution

  • config is of type AxiosRequestConfig, thus cannot be undefined.

    On the other hand, config.header can indeed be. As it's a Record (export type AxiosRequestHeaders = Record<string, string>;), you can indeed default it with an empty object:

    loggedInAxios.interceptors.request.use(
      async (config: AxiosRequestConfig) => {
        config.headers = config.headers ?? {};
    
        // Now config.headers can be safely used
        config.headers.Authorization = `...`
    
        return config;
      },
      (error) => error
    );