npm package
axios-auth-refresh review
Use axios-auth-refresh when your application already owns authentication and needs shared Axios renewal logic.
axios-auth-refresh 5.0.2 helps an existing Axios application renew credentials after a matching response error. You provide a promise-returning refresh callback; the interceptor waits for it and resends the failed request. A temporary request interceptor makes new requests wait during renewal. With default deduplication, another request already in flight can reject if its error reaches the response interceptor while the instance is paused. Authentication endpoints, token storage and sign-out policy remain application work.
Use axios-auth-refresh when your application already owns authentication and needs shared Axios renewal logic. Check the already-in-flight error path and test onRetry with your chosen retry instance before adopting it.
Answers from our run
axios-auth-refresh or axios: which should you use?
axios: Use Axios response interceptors directly when you want to implement and maintain the renewal state machine yourself. Axios documents request and response interception. Use axios-auth-refresh when your application already owns authentication and needs shared Axios renewal logic.
When should you not use axios-auth-refresh?
You need account management, sign-in routes or refresh-token issuance rather than an Axios interceptor.
Use it if
Skip it if
Setup reality
Install axios-auth-refresh@5.0.2 alongside an Axios version your application has reviewed and pinned. Published metadata declares Axios >= 1.0.0 as a peer dependency and provides import, require and TypeScript declaration entries. Those entries do not establish a tested compatibility matrix. This guide uses the supplied README, published bundle and package metadata. We did not install the package, execute the examples, run a security audit or test an authentication service. Every snippet below is an unexecuted documentation-based illustration.
Use a dedicated API instance and a separate transport for renewal. The refresh callback must return a promise and reject when renewal fails. Save the new access token before resolving, and update the failed request's Authorization header. Returning a token alone does not update that header. The example assumes a browser application and a server that already manages the refresh cookie and CSRF policy. Its module memory disappears on reload, so the application needs a session bootstrap path. Do not share that token variable across users in a server process.
The published 5.0.2 bundle establishes the response ordering missing from a helper-only reading. With deduplication enabled, the response handler adds the Axios instance to skipInstances before invoking the refresh callback. Its interception predicate returns false for that paused instance, and the response handler immediately returns Promise.reject(error) when the predicate is false. Consequently, an already-running request whose authentication error reaches this handler during the pause can reject without joining the refresh. New requests instead encounter the temporary request queue. These are source-derived paths, not measured timing results.
The original replay also needs a precise explanation. The bundle resends the failed request in a then callback and removes the temporary queue in finally, after that replay settles. With the default retry instance, the replay therefore passes through the still-installed request queue and can invoke onRetry. With a separate retryInstance, this plugin's queue remains on the original instance, so do not assume onRetry runs on that separate client's replay. Keep the explicit failed-request header update in refreshAuth for either configuration.
The replay receives skipAuthRefresh: true, so a further authentication failure does not trigger another refresh through this handler. When renewal rejects, queued requests receive an Axios cancellation error while the triggering request receives the refresh rejection. Handle these outcomes in your application without repeated sign-in redirects. A failed request and a newly queued request do not necessarily produce the same error.
Keep shouldRefresh narrow because it replaces the statusCodes predicate. A permission-denied 403 does not by itself establish renewable expiry. Leave interceptNetworkError disabled unless you have investigated the API's transport and CORS behavior. The supplied existing Axios guide covers general client configuration. Before adoption, exercise refresh success, refresh rejection, a replayed authentication failure and a second request already in flight. Check onRetry with the retry instance you actually use.
Ratings use a documentation-and-source rubric from 1 to 5. A score of 1 indicates a serious limitation for the dimension, 3 indicates usable evidence with material caveats, and 5 requires unusually complete supporting evidence. API stability considers the exposed contract and upgrade evidence; documentation considers setup guidance and consequential omissions; maintenance considers release evidence and implementation safeguards; ecosystem considers declared integration boundaries. These are editorial judgments, not measurements of adoption, support speed, security or runtime compatibility. No dimension receives extra credit for unknown evidence.
Patterns
Wire renewal and current-token headers wire-refresh
import axios from 'axios';
import { createAuthRefresh } from 'axios-auth-refresh';
export const api = axios.create({ baseURL: '/api', timeout: 10000 });
const refreshTransport = axios.create({ baseURL: '/api', timeout: 10000 });
let accessToken;
api.interceptors.request.use((config) => {
if (accessToken) config.headers.set('Authorization', `Bearer ${accessToken}`);
else config.headers.delete('Authorization');
return config;
});
export async function refreshAuth(failedRequest) {
const { data } = await refreshTransport.post('/session/refresh', null, {
withCredentials: true,
});
if (typeof data?.accessToken !== 'string' || !data.accessToken) {
throw new Error('Refresh response has no access token');
}
accessToken = data.accessToken;
failedRequest.response.config.headers['Authorization'] = `Bearer ${accessToken}`;
}
export const refreshInterceptorId = createAuthRefresh(api, refreshAuth);Unexecuted browser illustration using axios-auth-refresh@5.0.2. Save as api-client.js. The endpoint and response shape are application assumptions. Your server must supply cookie and CSRF handling. The separate refresh transport has no refresh interceptor; module token state must not be shared across server users.
Handle a protected request's rejection read-protected-resource
import { api } from './api-client.js';
try {
const { data } = await api.get('/profile');
console.log(data);
} catch (error) {
console.error('Profile request failed', error);
}Unexecuted illustration. Your application chooses retry or sign-in UI. Renewal failure, replay failure and an already-in-flight error during the pause can still reach caller error handling.
Exclude a request from response refresh handling skip-auth-refresh
import { api } from './api-client.js';
const response = await api.get('/public-status', {
skipAuthRefresh: true,
});
console.log(response.status);Unexecuted illustration. This flag bypasses the response refresh predicate. It does not remove token-injection headers or exempt the request from the temporary request queue.
Choose the API's expiry statuses choose-status-codes
// Replace the registration line in api-client.js.
export const refreshInterceptorId = createAuthRefresh(api, refreshAuth, {
statusCodes: [401],
});Unexecuted variation. 401 is the default. Add another status only when your API defines it as renewable expiry. Replace the existing registration rather than adding another handler.
Require a specific expiry code match-expiry-code
// Replace the registration line in api-client.js.
export const refreshInterceptorId = createAuthRefresh(api, refreshAuth, {
shouldRefresh: (error) =>
error.response?.status === 401 &&
error.response?.data?.code === 'ACCESS_TOKEN_EXPIRED',
});Unexecuted variation with an assumed service-specific code. shouldRefresh replaces the statusCodes predicate, so include the required status check here. The implementation catches synchronous callback exceptions, logs them and returns false.
Update headers in the temporary queue update-queued-config
// Replace the registration line in api-client.js.
export const refreshInterceptorId = createAuthRefresh(api, refreshAuth, {
onRetry: (config) => {
if (accessToken) config.headers.set('Authorization', `Bearer ${accessToken}`);
return config;
},
});Unexecuted variation. onRetry runs in the temporary request interceptor. With the default retry instance, the original replay also passes through that queue before cleanup. A separate retryInstance does not acquire this queue. Keep refreshAuth's failed-request header update for that configuration.
Choose a separate replay client choose-replay-instance
// In api-client.js, before registration:
const replayApi = axios.create({ baseURL: '/api', timeout: 10000 });
// Replace the original registration line.
export const refreshInterceptorId = createAuthRefresh(api, refreshAuth, {
retryInstance: replayApi,
});Unexecuted variation. The original failed request is resent through replayApi, while this plugin's temporary queue stays on api. Preserve the explicit failed-request header update. Review destination handling and any interceptors on the separate client.
Remove the response handler after work settles remove-refresh-interceptor
import { api, refreshInterceptorId } from './api-client.js';
// Wait for outstanding requests and refresh work before teardown.
api.interceptors.response.eject(refreshInterceptorId);Unexecuted illustration. Registration returns the response interceptor ID. Ejecting that handler does not cancel active requests or remove the separate token-injection interceptor. Test lifecycle handling if teardown can overlap renewal.
Alternatives
| Package | Registry | Pick it when |
|---|---|---|
| axios | npm | Use Axios response interceptors directly when you want to implement and maintain the renewal state machine yourself. Axios documents request and response interception. |
| axios-retry | npm | Consider axios-retry for a general retry policy. Its documented default retries network errors or 5xx errors on idempotent requests. Token renewal requires an explicit retry condition and renewal callback. |
More data guides
How this guide is made: grounded in the library's documentation, release notes, changelog, and issue history, on a fixed rubric — not a hands-on install of every release. The 50 most-downloaded entries are additionally install-verified in clean containers. Corrections: contact the desk.