import axios, { AxiosInstance } from "axios";
import { v4 as uuidv4 } from 'uuid';
const axiosInstance: AxiosInstance = axios.create({
baseURL: "http://localhost:8080",
timeout: 10000, // 10 s
headers: {
"Content-Type": "application/json",
},
});
axiosInstance.interceptors.request.use(config => {
// Generate a unique correlation ID
const correlationId = uuidv4();
// Attach the correlation ID to the headers
if (config.headers) {
config.headers['X-Correlation-ID'] = correlationId;
} else {
config.headers = {
'corRelationId': correlationId,
};
}
return config;
}, error => {
return Promise.reject(error);
});
export default axiosInstance;
I'm trying to create corRelationId dynamically send every request but i'm getting error
Error TS2322: Type '{ corRelationId: string; }' is not assignable to type 'AxiosRequestHeaders'. Type '{ corRelationId: string; }' is missing the following properties from type 'AxiosHeaders': set, get, has, delete, and 23 more. 19 | config.headers['X-Correlation-ID'] = correlationId; 20 | } else {
21 | config.headers = { | ^^^^^^^^^^^^^^ 22 | 'corRelationId': correlationId, 23 | }; 24 | }
AxiosRequestHeaders
isn't a plain object which is why TypeScript is complaining. See https://github.com/axios/axios?tab=readme-ov-file#-axiosheaders
It's also never optional so there's no need for your check...
interface InternalAxiosRequestConfig<D = any> extends AxiosRequestConfig<D> { headers: AxiosRequestHeaders; // 👈 not optional }
Simply set the header key / value pair that you want. You should also use the set()
method as direct property access is deprecated
// Don't blanket-set content-type headers
const axiosInstance: AxiosInstance = axios.create({
baseURL: 'http://localhost:8080',
timeout: 10000, // 10 s
});
axiosInstance.interceptors.request.use((config) => {
const correlationId = uuidv4();
config.headers.set('X-Correlation-ID', correlationId);
return config;
}, null, { synchronous: true });
Some notes:
content-type
headers for all requests. It's redundant and can easily lead to confusion / mistakesnull
for the 2nd interceptor onRejected
parameter to simply use the default{ synchronous: true }
if your interceptor is synchronous for better optimisation