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

Viewed 6314

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...

2 Answers

You can either use ! (non-nullable assertion operator) to tell TypeScript that a property is not undefined or null (assuming you are 100% SURE), or check it and assign it if it's undefined.

Example 1:

config.headers!.Authorization = `Bearer ${accessToken}`;

Example 2:

config.headers = config.headers ?? {};

Example 3:

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

I don't think there are any another ways.

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) => {
    if (config.headers === undefined) {
      config.headers = {};
    }
    // ...
    return config;
  },
  (error) => error
);
Related