How axios-auth-refresh works
masterThe library uses Axios interceptors to watch for specific failure status codes (defaulting to 401 Unauthorized). When a failure occurs, it executes a provided refreshAuthLogic function.
Key behaviors:
- Request Stalling: While the refresh logic is running, any additional incoming requests are automatically stalled (queued).
- Automatic Resolution: Once the refresh logic resolves, the stalled requests are retried with the updated configuration. If the refresh logic fails, the stalled requests are rejected.
- Deduplication: By default, only one refresh cycle runs at a time, even if multiple requests fail simultaneously. This prevents multiple redundant refresh calls.
import axios from 'axios';
import { createAuthRefresh } from 'axios-auth-refresh';
// Function that will be called to refresh authorization
const refreshAuthLogic = (failedRequest) =>
axios.post('https://www.example.com/auth/token/refresh').then((tokenRefreshResponse) => {
localStorage.setItem('token', tokenRefreshResponse.data.token);
failedRequest.response.config.headers['Authorization'] = 'Bearer ' + tokenRefreshResponse.data.token;
return Promise.resolve();
});
// Instantiate the interceptor
createAuthRefresh(axios, refreshAuthLogic);