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

88
Views
Axios interceptors runs more than once

I have this interceptors that logs the user out if unauthorized. I do, however, get more than a 401 response, and the interceptors does therefore run for as many times as the responses I get (4). Is there a way to make it run only for the first one?

This is my code:

api.interceptors.response.use(
(response) => response,
(err) => {
  if (err.response.status === 401 && isLoggedIn) {
    api
      .delete("auth/sign_out")
      .then((resp) => {
        clearLocalStorage();
      })
      .catch((err) => {
        clearLocalStorage();
      });
  } else {
    return Promise.reject(err);
  }
  return err;
}

);

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

0

You might want something like this to "lock out" the possible re-entrant calls:

let isLoggingOut = false; // global

// ...

api.interceptors.response.use(
  (response) => response,
  async (err) => {
    if (err.response.status === 401 && isLoggedIn) {
      if(!isLoggingOut) {
        isLoggingOut = true;  // disallow re-entrant calls
        try {
          await api.delete('auth/sign_out');
        } catch (deletionError) {
          // throw errors away
        } finally {
          clearLocalStorage();
          isLoggingOut = false;
          isLoggedIn = false; // if the variable is assignable
        }
      }
    }
    return err;
  },
);
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!