Documentation
GitHubaxios-token-refresh
axios-token-refresh is a lightweight utility for handling token refresh logic in Axios. It integrates seamlessly with Axios interceptors to automatically retry requests after token expiration. Perfect for authentication flows in modern web applications.
Installation
npm install axios-token-refresh
Basic Usage
import axios from 'axios';
import registerAxiosTokenRefresh from 'axios-token-refresh';
const api = axios.create({ baseURL: '/api' });
registerAxiosTokenRefresh(api, {
refreshRequest: async (error) => {
// Call your refresh token API
const res = await axios.post('/auth/refresh', { token: 'refresh-token' });
// Attach new accessToken to header
error.config.headers['Authorization'] = 'Bearer ' + res.data.accessToken;
return api.request(error.config);
},
});
API Options
- refreshRequest: (required) The function to handle token refresh, must return a Promise.
- statusCodes: (optional) List of status codes that trigger refresh (default:
[401]
). - shouldRetry: (optional) Custom function to determine if refresh should occur.
- retryTimes: (optional) Number of retry attempts (default:
1
). - onRetry: (optional) Callback before each refresh attempt.