question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Interceptors - how to prevent intercepted messages from resolving as error

See original GitHub issue

I’m trying to make an interceptor for 401 responses that result from expired token. Upon interception I want to login and retry the requests with the new token. My problem is that login is also done asynchronously, so by the time the retry happens, the original promises reject. Is there a way around that? Here’s my code:

axios.interceptors.response.use(undefined, err => {
  if (err.status === 401 && err.config && !err.config.__isRetryRequest) {
    refreshLogin(getRefreshToken(),
      success => {
        setTokens(success.access_token, success.refresh_token)
        err.config.__isRetryRequest = true
        err.config.headers.Authorization = 'Bearer ' + getAccessToken()
        axios(err.config)
      },
      error => { console.log('Refresh login error: ', error) }
    )
  }
})

Issue Analytics

  • State:closed
  • Created 8 years ago
  • Reactions:2
  • Comments:33 (2 by maintainers)

github_iconTop GitHub Comments

89reactions
geocinecommented, Oct 5, 2016

You could do something like this:

axios.interceptors.response.use(function (response) {
  return response;
}, function (error) {

  const originalRequest = error.config;

  if (error.response.status === 401 && !originalRequest._retry) {

    originalRequest._retry = true;

    const refreshToken = window.localStorage.getItem('refreshToken');
    return axios.post('http://localhost:8000/auth/refresh', { refreshToken })
      .then(({data}) => {
        window.localStorage.setItem('token', data.token);
        window.localStorage.setItem('refreshToken', data.refreshToken);
        axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.token;
        originalRequest.headers['Authorization'] = 'Bearer ' + data.token;
        return axios(originalRequest);
      });
  }

  return Promise.reject(error);
});
47reactions
mzabriskiecommented, Jul 16, 2016

Sorry for the delay, I am just seeing this issue.

You need to make a return statement from your interceptor which will keep the Promise alive. More or less change your refreshLogin to return a Promise and then return that from your interceptor.

Or if you can’t refactor refreshLogin you can wrap it in a Promise.

axios.interceptors.response.use(undefined, err => {
  let res = err.response;
  if (res.status === 401 && res.config && !res.config.__isRetryRequest) {
    return new Promise((resolve, reject) => {
      refreshLogin(getRefreshToken(),
        success => {
          setTokens(success.access_token, success.refresh_token)
          err.config.__isRetryRequest = true
          err.config.headers.Authorization = 'Bearer ' + getAccessToken()
          resolve(axios(err.config))
        },
        error => {
          console.log('Refresh login error: ', error)
          reject(error)
        }
      )
    });
  }
})
Read more comments on GitHub >

github_iconTop Results From Across the Web

How to use Axios interceptors to handle API error responses
One way to solve this problem, is to handle it when you do the request in your code, so if you have an...
Read more >
Chapter 18. Intercepting Messages Red Hat AMQ 7.0
Interceptors must implement the intercept() method, which returns a boolean value. If the value is true , the message packet continues onward. If...
Read more >
How to prevent axios.interceptors.response.use to crash the ...
I have several forms "Login, Registration, Create a product..." For these forms, I was handling errors with useState for the front end and...
Read more >
4 ways to use Axios interceptors | Khaled Garbaya
Error handling using Axios interceptors ... You can use An Axios interceptor to capture all errors and enhance them before reaching your end...
Read more >
Angular: Handle HTTP Errors using Interceptors
Interceptors are a unique type of Angular service that we can implement. Interceptors allow us to intercept incoming or outgoing HTTP ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found