Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

192
Views
How can I use Axios interceptors to add some headers to responses?

In my Reactjs app , I want to add an interceptor which can append some headers to some backend responses

So, I tried this :

    export default function App() {
      axios.interceptors.response.use(
        (config)=> {
          config.headers['myheader'] = 'myvalue'; // <-- THIS IS MY CUSTOM HEADERS
          return config;
        },
        (error) => {
          // ON ERREOR
        })
       ......
      );

And I suppose like that that my header would be append in every back-end response. But that doesn't seem to work.

Suggestions ??

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Add a request interceptor

axios.interceptors.request.use(
    config => {
        const token = localStorage.getItem('auth_token');
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        config.headers['Content-Type'] = 'application/json';
        return config;
    },
    error => {
        Promise.reject(error)
});

Add a response interceptor

axios.interceptors.response.use((response) => { // block to handle success case
    return response
 }, function (error) { // block to handle error case
    const originalRequest = error.config;
 
    if (error.response.status === 401 && originalRequest.url ===
 'http://dummydomain.com/auth/token') { // Added this condition to avoid infinite loop 

 
        // Redirect to any unauthorised route to avoid infinite loop...
        return Promise.reject(error);
    }
 
    if (error.response.status === 401 && !originalRequest._retry) { // Code inside this block will refresh the auth token
 
        originalRequest._retry = true;
        const refreshToken = 'xxxxxxxxxx'; // Write the  logic  or call here the function which is having the login to refresh the token.
        return axios.post('/auth/token',
            {
                "refresh_token": refreshToken
            })
            .then(res => {
                if (res.status === 201) {
                    localStorage.setItem('auth_token',res.data);
                    axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('auth_token');
                    return axios(originalRequest);
                }
            })
    }
    return Promise.reject(error);
});

Click here to see the topic in detail.

about 4 years ago · Juan Pablo Isaza Report

0

Try this:

    axios.interceptors.response.use(
      function (response) {
        const edited_response = response;
        edited_response.headers["custom_header"] = "test";
        return edited_response;
      },
      function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
      }
    );
about 4 years ago · Juan Pablo Isaza Report

0

Hey the reason thats not working because you are calling use method to update the repsonse headers but to be able to send headers to your backend apis you need to call the use method from request object. Here's how you can do :

axios.interceptors.request.use(
  function handleRequestInterceptor(config) {
    const modifiedConfig = {
      ...config,
      headers: {
        myheader: "myvalue",  <=== your custom headers like auth etc.
        ...config.headers,
      },
    };
    return modifiedConfig;
  },
  function handleRequestInterceptorError(error) {
    return Promise.reject(error);
  }
);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!