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.

Handling refresh token by recall same request after refreshing the token

See original GitHub issue

Hi, I am trying to make a common interceptor to authorize all my outgoing requests.

My logic is as follows:

All my outgoing requests/API calls passes through the interceptor first to check on my token expiry and in-case the response was un-authorized I make an internal call to refresh the token and update my storage keys with the new values.

Now I need to recall the original request with the new token value, but I can’t figure out how to detect the original request that passed through the interceptor.

This is my code :

export  const unregister =  fetchIntercept.register({
  request: function (url, config) {
    return [url, config];
  },

  requestError: function (error) {
    return Promise.reject(error);
  },
  responseError: function (error) {
    return Promise.reject(error);
  },

  response: function (response) {
    if (response.status == 401) {
      Services.refreshToken((res)=>{
        if (res.message == 'success') {
          // if token has been refreshed
          // recall the request again
        }else {
          // login again
        }
      })
    }else {
      return response;
    }
  }
})

The problem is that I’ve no idea how to recall the same request that passed through the interceptor… I did some search on this, but couldn’t find a way to execute this.

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:7

github_iconTop GitHub Comments

1reaction
vitorcamachoocommented, May 31, 2021

Here is example of refresh token and recall the original request

const originalRequest = {}
export const interceptor = fetchIntercept.register({    
    request: function (url, config) {
        originalRequest.url = url
        originalRequest.config = config
        return [url, config];
    },
 
    requestError: function (error) {
        // Called when an error occured during another 'request' interceptor call        
        return Promise.reject(error);
    },
 
    response: async function (response) {
        if(response.status === 401)
        {
            const {url, config} = originalRequest
            if(url.includes('token'))
            {
                interceptor()
                return Promise.reject("Session expired");
            }
            else
            {                
                return AppStore.dispatch(AuthActions.refresh_token())
                        .then((data) => {
                            config['headers']['Authorization'] = 'Bearer '+data.token
                            return fetch(url, config)
                        })
                        .catch((error) => {
                            return Promise.reject(error)
                        })                            
            }            
        }
        else
        {
            return response
        }        
    },
 
    responseError: function (error) {
        // Handle an fetch error
        return Promise.reject(error);
    }
});

This will not work if multiple requests were made in parallel. It will use the wrong url and config

1reaction
ovaisscommented, Apr 6, 2021

Here is example of refresh token and recall the original request

const originalRequest = {}
export const interceptor = fetchIntercept.register({    
    request: function (url, config) {
        originalRequest.url = url
        originalRequest.config = config
        return [url, config];
    },
 
    requestError: function (error) {
        // Called when an error occured during another 'request' interceptor call        
        return Promise.reject(error);
    },
 
    response: async function (response) {
        if(response.status === 401)
        {
            const {url, config} = originalRequest
            if(url.includes('token'))
            {
                interceptor()
                return Promise.reject("Session expired");
            }
            else
            {                
                return AppStore.dispatch(AuthActions.refresh_token())
                        .then((data) => {
                            config['headers']['Authorization'] = 'Bearer '+data.token
                            return fetch(url, config)
                        })
                        .catch((error) => {
                            return Promise.reject(error)
                        })                            
            }            
        }
        else
        {
            return response
        }        
    },
 
    responseError: function (error) {
        // Handle an fetch error
        return Promise.reject(error);
    }
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

reactjs - Handling refresh token by recall same request after ...
My logic is as follows: All my outgoing requests/API calls passes through the interceptor first to check on my token expiry and in-case...
Read more >
Handling refresh token by recall same request after ... - GitHub
Hi, I am trying to make a common interceptor to authorize all my outgoing requests. My logic is as follows: All my outgoing...
Read more >
Handle Refresh Tokens with Axios - JavaScript in Plain English
This is an issue that happens when we call multiple requests with an expired token at the same time. It will make multiple...
Read more >
Using Axios interceptors for refreshing your API token.
I'm using Redis to store the token and refresh token received from the API as you can see in the examples. Obvious code...
Read more >
What Are Refresh Tokens and How to Use Them Securely
A refresh token can help you balance security with usability. Since refresh tokens are typically longer-lived, you can use them to request new ......
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