Gathering detailed insights and metrics for axios-auth-refresh
Gathering detailed insights and metrics for axios-auth-refresh
Gathering detailed insights and metrics for axios-auth-refresh
Gathering detailed insights and metrics for axios-auth-refresh
@plansis/axios-auth-refresh
Этот простой модуль обеспечивает отправку единого запроса на обновление токена даже при обработке одновременных запросов. Кроме того, он предлагает методы для последовательной интеграции запросов Axios с различными библиотеками.
@blueberry6401/axios-auth-refresh
Axios plugin which makes it very easy to automatically refresh the authorization tokens of your clients
axios-auth-refresh-response-data
Axios plugin which makes it very easy to automatically refresh the authorization tokens of your clients. In this fork, axios request returns response.data.
axios-token-manager
A manager for Auth Tokens using Axios in a Node API Server or a JS Client
Library that helps you implement automatic refresh of authorization via axios interceptors. You can easily intercept the original request when it fails, refresh the authorization and continue with the original request, without user even noticing.
npm install axios-auth-refresh
Typescript
Module System
Node Version
NPM Version
97.4
Supply Chain
98.3
Quality
75.4
Maintenance
100
Vulnerability
100
License
TypeScript (96.43%)
JavaScript (3.26%)
Shell (0.3%)
Total Downloads
15,244,163
Last Day
2,442
Last Week
79,909
Last Month
333,508
Last Year
3,870,419
MIT License
1,094 Stars
161 Commits
90 Forks
9 Watchers
9 Branches
17 Contributors
Updated on Jul 04, 2025
Minified
Minified + Gzipped
Latest Version
3.3.6
Package Id
axios-auth-refresh@3.3.6
Unpacked Size
30.66 kB
Size
9.61 kB
File Count
8
NPM Version
8.5.0
Node Version
16.14.0
Cumulative downloads
Total Downloads
Library that helps you implement automatic refresh of authorization via axios interceptors. You can easily intercept the original request when it fails, refresh the authorization and continue with the original request, without any user interaction.
What happens when the request fails due to authorization is all up to you. You can either run a refresh call for a new authorization token or run a custom logic.
The plugin stalls additional requests that have come in while waiting for a new authorization token and resolves them when a new token is available.
1npm install axios-auth-refresh --save 2# or 3yarn add axios-auth-refresh
1createAuthRefreshInterceptor( 2 axios: AxiosInstance, 3 refreshAuthLogic: (failedRequest: any) => Promise<any>, 4 options: AxiosAuthRefreshOptions = {} 5): number;
axios
- an instance of AxiosrefreshAuthLogic
- a Function used for refreshing authorization (must return a promise).
Accepts exactly one parameter, which is the failedRequest
returned by the original call.options
- object with settings for interceptor (See available options)Interceptor id
in case you want to reject it manually.
In order to activate the interceptors, you need to import a function from axios-auth-refresh
which is exported by default and call it with the axios instance you want the interceptors for,
as well as the refresh authorization function where you need to write the logic for refreshing the authorization.
The interceptors will then be bound onto the axios instance, and the specified logic will be run whenever a 401 (Unauthorized) status code is returned from a server (or any other status code you provide in options). All the new requests created while the refreshAuthLogic has been processing will be bound onto the Promise returned from the refreshAuthLogic function. This means that the requests will be resolved when a new access token has been fetched or when the refreshing logic failed.
1import axios from 'axios'; 2import createAuthRefreshInterceptor from 'axios-auth-refresh'; 3 4// Function that will be called to refresh authorization 5const refreshAuthLogic = (failedRequest) => 6 axios.post('https://www.example.com/auth/token/refresh').then((tokenRefreshResponse) => { 7 localStorage.setItem('token', tokenRefreshResponse.data.token); 8 failedRequest.response.config.headers['Authorization'] = 'Bearer ' + tokenRefreshResponse.data.token; 9 return Promise.resolve(); 10 }); 11 12// Instantiate the interceptor 13createAuthRefreshInterceptor(axios, refreshAuthLogic); 14 15// Make a call. If it returns a 401 error, the refreshAuthLogic will be run, 16// and the request retried with the new token 17axios.get('https://www.example.com/restricted/area').then(/* ... */).catch(/* ... */);
:warning: Because of the bug axios#2295 v0.19.0 is not supported. :warning:
:white_check_mark: This has been fixed and will be released in axios v0.19.1
There's a possibility to skip the logic of the interceptor for specific calls.
To do this, you need to pass the skipAuthRefresh
option to the request config for each request you don't want to intercept.
1axios.get('https://www.example.com/', { skipAuthRefresh: true });
If you're using TypeScript you can import the custom request config interface from axios-auth-refresh
.
1import { AxiosAuthRefreshRequestConfig } from 'axios-auth-refresh';
Since this plugin automatically stalls additional requests while refreshing the token, it is a good idea to wrap your request logic in a function, to make sure the stalled requests are using the newly fetched data (like token).
Example of sending the tokens:
1// Obtain the fresh token each time the function is called 2function getAccessToken() { 3 return localStorage.getItem('token'); 4} 5 6// Use interceptor to inject the token to requests 7axios.interceptors.request.use((request) => { 8 request.headers['Authorization'] = `Bearer ${getAccessToken()}`; 9 return request; 10});
You can specify multiple status codes that you want the interceptor to run for.
1{ 2 statusCodes: [401, 403], // default: [ 401 ] 3}
You can specify multiple status codes that you want the interceptor to run for.
1{ 2 shouldRefresh: (error) => 3 error?.response?.data?.business_error_code === 100385, 4}
You can specify the instance which will be used for retrying the stalled requests.
Default value is undefined
and the instance passed to createAuthRefreshInterceptor
function is used.
1{ 2 retryInstance: someAxiosInstance, // default: undefined 3}
onRetry
callback before sending the stalled requestsYou can specify the onRetry
callback which will be called before each
stalled request is called with the request configuration object.
1{ 2 onRetry: (requestConfig) => ({ ...requestConfig, baseURL: '' }), // default: undefined 3}
While your refresh logic is running, the interceptor will be triggered for every request
which returns one of the options.statusCodes
specified (HTTP 401 by default).
In order to prevent the interceptors loop (when your refresh logic fails with any of the status
codes specified in options.statusCodes
) you need to use a skipAuthRefresh
flag on your refreshing call inside the refreshAuthLogic
function.
In case your refresh logic does not make any calls, you should consider using the following flag when initializing the interceptor to pause the whole axios instance while the refreshing is pending. This prevents interceptor from running for each failed request.
1{ 2 pauseInstanceWhileRefreshing: true, // default: false 3}
Some CORS APIs may not return CORS response headers when an HTTP 401 Unauthorized response is returned. In this scenario, the browser won't be able to read the response headers to determine the response status code.
To intercept any network error, enable the interceptNetworkError
option.
CAUTION: This should be used as a last resort. If this is used to work around an API that doesn't support CORS with an HTTP 401 response, your retry logic can test for network connectivity attempting refresh authentication.
1{ 2 interceptNetworkError: true, // default: undefined 3}
This library has also been used for:
have you used it for something else? Create a PR with your use case to share it.
v3.1.0
interceptNetworkError
option introduced. See #133.v3.0.0
skipWhileRefresh
flag has been deprecated due to its unclear name and its logic has been moved to pauseInstanceWhileRefreshing
flagpauseInstanceWhileRefreshing
is set to false
by defaultCheck out contribution guide or my patreon page!
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
Found 3/14 approved changesets -- score normalized to 2
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
12 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-06-30
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreLast Day
17.7%
2,442
Compared to previous day
Last Week
-2%
79,909
Compared to previous week
Last Month
0.1%
333,508
Compared to previous month
Last Year
1.9%
3,870,419
Compared to previous year