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

3

13

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

Eccrine answered 23/11, 2021 at 17:24 Comment(0)
E
24

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
);
Ethbin answered 26/11, 2021 at 11:32 Comment(0)
P
28

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.

Porta answered 23/11, 2021 at 18:35 Comment(0)
E
24

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
);
Ethbin answered 26/11, 2021 at 11:32 Comment(0)
S
0

I suggest using InternalAxiosRequestConfig from axios, then you won't need any config.headers = config.headers ?? {}; "hack" as suggested in other answers.

Example:

const onFulfilled = async (config: InternalAxiosRequestConfig) => {
    config.headers.Authorization = `Bearer YOUR_TOKEN`;
    return config;
};

// and then use it like
axiosInstance.interceptors.request.use(onFulfilled, onRejected)
Spiroid answered 11/8, 2024 at 11:52 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.