notable-jade
notable-jade3y ago

How to add Header into request GLOBALLY

I want to add a header for each api call, since my API requires a X-API-KEY header. Anyone know how?
6 Replies
refine-support-bot
Hi, I am refine support bot :wave:. I am here to help you with your question. I searched for the answer to your question in the refine documentation and found an answer! 🏆
Answer: You can use axios.interceptors.request.use to add the X-API-KEY header to each API call. SOURCES: ./docs/tutorial/5-understanding-authprovider/1-create-authprovider.md, ./docs/api-reference/core/hooks/data/useCustom/index.md

Note: If this is the answer you need, then we are very lucky. If not, please wait for someone from the refine core team or the community to try to help you.
notable-jade
notable-jadeOP3y ago
?
grumpy-cyan
grumpy-cyan3y ago
you can use axios interceptors to do that for example: in tutorial we demonstrate how to do this: https://refine.dev/docs/tutorial/understanding-authprovider/create-authprovider/#setting-authorization-credentials
axiosInstance.interceptors.request.use(
(request: AxiosRequestConfig) => {
if (request.headers) {
request.headers = {
"x-api-key": API_KEY,
};
}
return request;
},
);
axiosInstance.interceptors.request.use(
(request: AxiosRequestConfig) => {
if (request.headers) {
request.headers = {
"x-api-key": API_KEY,
};
}
return request;
},
);
if you are using simple-rest, simple-rest accepts httpClient as a second parameter. you can create your own axiosInstance and pass it to simple-rest
notable-jade
notable-jadeOP3y ago
@alicanerdurmaz thank you very much It does give my an mismatch type error Saying 'axios' is not assignable to parameter of refine They're two different interfaces And I import {axios}
axiosInstance.interceptors.request.use((request: any) => {
if(request.headers) {
console.log(request.headers)
request.headers = {
...request.headers,
"x-api-key": "1234567890",
};
}
return request
})
axiosInstance.interceptors.request.use((request: any) => {
if(request.headers) {
console.log(request.headers)
request.headers = {
...request.headers,
"x-api-key": "1234567890",
};
}
return request
})
Trying this but no luck unfortunate
grumpy-cyan
grumpy-cyan3y ago
are you using simple-rest ? and, please can you give me your implementation details to debug ?
Omer
Omer3y ago
Hey @raulfernandez 👋 , Is the correct version installed? The 'refine simple-rest' data provider is using version 0.26 of axios. https://github.com/refinedev/refine/blob/next/packages/simple-rest/package.json#L39
npm install axios@0.26
npm install axios@0.26

Did you find this page helpful?