Home > Net >  Why `config.headers` in interceptor is possibly undefined
Why `config.headers` in interceptor is possibly undefined

Time:10-12

I'm new in nodejs so it gets hard to me to fix some problems, thank you in advance. So here is my .../src/http/index.ts file

import axios from 'axios'

export const API_URL = `http://localhost:5000/api`

const $api = axios.create({
    withCredentials: true,
    baseURL: API_URL
})

$api.interceptors.request.use((config) => {
    config.headers.Authorization= `Bearer ${localStorage.getItem('token')}`
    return config
})

export default $api 

and config.headers in here is underlined and ts shows me that

Object is possibly 'undefined'.  TS2532
12 |
13 | $api.interceptors.request.use((config) => {
14 |     config.headers.Authorization= `Bearer ${localStorage.getItem('token')}`
   |     ^
15 |     return config
16 | })
17 |

I've just thinking on it so long and can't get what the problem is

AxiosRequestConfig.headers?: Record<string, string>

CodePudding user response:

The error tells you that the way Axios defines its TypeScript types for its API, config may be undefined when your interceptor function is called. (And it looks that way in the TypeScript playground as well.) The interceptors documentation doesn't say anything either way, which seems odd.

If you're sure that the config parameter will never be undefined, you can include an assertion saying that:

$api.interceptors.request.use((config) => {
    if (!config?.headers) {
        throw new Error(`Expected 'config' and 'config.headers' not to be undefined`);
    }
    config.headers.Authorization= `Bearer ${localStorage.getItem('token')}`;
    return config;
});

If you're incorrect, that will result in a runtime error.

If you aren't sure, you could create the config if needed:

$api.interceptors.request.use((config) => {
    if (!config) {
        config = {};
    }
    if (!config.headers) {
        config.headers = {};
    }
    config.headers.Authorization= `Bearer ${localStorage.getItem('token')}`;
    return config;
});
  • Related