{"id":15026329,"url":"https://github.com/flyrell/axios-auth-refresh","last_synced_at":"2026-03-03T22:04:05.051Z","repository":{"id":40400076,"uuid":"158723630","full_name":"Flyrell/axios-auth-refresh","owner":"Flyrell","description":"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.","archived":false,"fork":false,"pushed_at":"2024-04-22T15:20:53.000Z","size":2623,"stargazers_count":1090,"open_issues_count":30,"forks_count":92,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-05-12T15:53:29.751Z","etag":null,"topics":["authentication","axios","axios-plugin","http-interceptor","interceptor","middleware","stalled-requests","token","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Flyrell.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-11-22T16:10:33.000Z","updated_at":"2025-04-30T04:50:36.000Z","dependencies_parsed_at":"2024-06-18T12:17:47.377Z","dependency_job_id":"f27c06f4-f051-4974-a71d-91040c95b186","html_url":"https://github.com/Flyrell/axios-auth-refresh","commit_stats":{"total_commits":135,"total_committers":21,"mean_commits":6.428571428571429,"dds":0.4740740740740741,"last_synced_commit":"6ea5f96bde9e1397a7445762f6106951eb5c6dfc"},"previous_names":[],"tags_count":35,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Flyrell%2Faxios-auth-refresh","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Flyrell%2Faxios-auth-refresh/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Flyrell%2Faxios-auth-refresh/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Flyrell%2Faxios-auth-refresh/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Flyrell","download_url":"https://codeload.github.com/Flyrell/axios-auth-refresh/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254083783,"owners_count":22011902,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","axios","axios-plugin","http-interceptor","interceptor","middleware","stalled-requests","token","typescript"],"created_at":"2024-09-24T20:04:17.163Z","updated_at":"2026-03-03T22:04:05.046Z","avatar_url":"https://github.com/Flyrell.png","language":"TypeScript","readme":"![Package version](https://img.shields.io/npm/v/axios-auth-refresh?label=version)\n![Package size](https://img.shields.io/bundlephobia/min/axios-auth-refresh)\n![Package downloads](https://img.shields.io/npm/dm/axios-auth-refresh)\n![Package types definitions](https://img.shields.io/npm/types/axios-auth-refresh)\n\n# axios-auth-refresh\n\nLibrary that helps you implement automatic refresh of authorization\nvia axios [interceptors](https://github.com/axios/axios#interceptors).\nYou can easily intercept the original request when it fails, refresh the authorization and continue with the original request,\nwithout any user interaction.\n\nWhat happens when the request fails due to authorization is all up to you.\nYou can either run a refresh call for a new authorization token or run a custom logic.\n\nThe plugin stalls additional requests that have come in while waiting for a new authorization token\nand resolves them when a new token is available.\n\n## Installation\n\nUsing [npm](https://www.npmjs.com/get-npm) or [yarn](https://yarnpkg.com/en/docs/install):\n\n```bash\nnpm install axios-auth-refresh --save\n# or\nyarn add axios-auth-refresh\n```\n\n## Syntax\n\n```typescript\ncreateAuthRefreshInterceptor(\n    axios: AxiosInstance,\n    refreshAuthLogic: (failedRequest: any) =\u003e Promise\u003cany\u003e,\n    options: AxiosAuthRefreshOptions = {}\n): number;\n```\n\n#### Parameters\n\n- `axios` - an instance of Axios\n- `refreshAuthLogic` - a Function used for refreshing authorization (**must return a promise**).\n  Accepts exactly one parameter, which is the `failedRequest` returned by the original call.\n- `options` - object with settings for interceptor (See [available options](#available-options))\n\n#### Returns\n\nInterceptor `id` in case you want to reject it manually.\n\n## Usage\n\nIn order to activate the interceptors, you need to import a function from `axios-auth-refresh`\nwhich is _exported by default_ and call it with the **axios instance** you want the interceptors for,\nas well as the **refresh authorization function** where you need to write the logic for refreshing the authorization.\n\nThe interceptors will then be bound onto the axios instance, and the specified logic will be run whenever a [401 (Unauthorized)](https://httpstatuses.com/401) status code\nis 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\nPromise 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.\n\n```javascript\nimport axios from 'axios';\nimport createAuthRefreshInterceptor from 'axios-auth-refresh';\n\n// Function that will be called to refresh authorization\nconst refreshAuthLogic = (failedRequest) =\u003e\n    axios.post('https://www.example.com/auth/token/refresh').then((tokenRefreshResponse) =\u003e {\n        localStorage.setItem('token', tokenRefreshResponse.data.token);\n        failedRequest.response.config.headers['Authorization'] = 'Bearer ' + tokenRefreshResponse.data.token;\n        return Promise.resolve();\n    });\n\n// Instantiate the interceptor\ncreateAuthRefreshInterceptor(axios, refreshAuthLogic);\n\n// Make a call. If it returns a 401 error, the refreshAuthLogic will be run,\n// and the request retried with the new token\naxios.get('https://www.example.com/restricted/area').then(/* ... */).catch(/* ... */);\n```\n\n#### Skipping the interceptor\n\nThere's a possibility to skip the logic of the interceptor for specific calls.\nTo do this, you need to pass the `skipAuthRefresh` option to the request config for each request you don't want to intercept.\n\n```javascript\naxios.get('https://www.example.com/', { skipAuthRefresh: true });\n```\n\nIf you're using TypeScript you can import the custom request config interface from `axios-auth-refresh`.\n\n```typescript\nimport { AxiosAuthRefreshRequestConfig } from 'axios-auth-refresh';\n```\n\n#### Request interceptor\n\nSince this plugin automatically stalls additional requests while refreshing the token,\nit is a good idea to **wrap your request logic in a function**,\nto make sure the stalled requests are using the newly fetched data (like token).\n\nExample of sending the tokens:\n\n```javascript\n// Obtain the fresh token each time the function is called\nfunction getAccessToken() {\n    return localStorage.getItem('token');\n}\n\n// Use interceptor to inject the token to requests\naxios.interceptors.request.use((request) =\u003e {\n    request.headers['Authorization'] = `Bearer ${getAccessToken()}`;\n    return request;\n});\n```\n\n## Available options\n\n#### Status codes to intercept\n\nYou can specify multiple status codes that you want the interceptor to run for.\n\n```javascript\n{\n    statusCodes: [401, 403], // default: [ 401 ]\n}\n```\n\n#### Customize intercept logic\n\nYou can provide a custom function to determine whether a failed request should trigger a refresh.\nWhen `shouldRefresh` is configured, the `statusCodes` logic is ignored.\n\n```javascript\n{\n    shouldRefresh: (error) =\u003e\n        error?.response?.data?.business_error_code === 100385,\n}\n```\n\n#### Retry instance for stalled requests\n\nYou can specify the instance which will be used for retrying the stalled requests.\nDefault value is `undefined` and the instance passed to `createAuthRefreshInterceptor` function is used.\n\n```javascript\n{\n    retryInstance: someAxiosInstance, // default: undefined\n}\n```\n\n#### `onRetry` callback before sending the stalled requests\n\nYou can specify the `onRetry` callback which will be called before each\nstalled request is called with the request configuration object.\n\n```javascript\n{\n    onRetry: (requestConfig) =\u003e ({ ...requestConfig, baseURL: '' }), // default: undefined\n}\n```\n\n#### Deduplicate refresh calls\n\nBy default (`deduplicateRefresh: true`), the interceptor ensures that only one refresh call runs at a time.\nWhile the refresh is in progress, the axios instance is paused — any new requests are queued and\nresolved automatically once the refresh completes.\n\nThis is the recommended behavior for most applications. If you need every failed request to independently\ntrigger its own refresh cycle, you can disable it:\n\n```javascript\n{\n    deduplicateRefresh: false, // default: true\n}\n```\n\nWhen disabled, you must mark your refresh calls with [`skipAuthRefresh`](#skipping-the-interceptor)\nto avoid interceptor loops.\n\n#### Intercept on network error\n\nSome CORS APIs may not return CORS response headers when an HTTP 401 Unauthorized response is returned.\nIn this scenario, the browser won't be able to read the response headers to determine the response status code.\n\nTo intercept _any_ network error, enable the `interceptNetworkError` option.\n\nCAUTION: This should be used as a last resort. If this is used to work around an API that doesn't support CORS\nwith an HTTP 401 response, your retry logic can test for network connectivity attempting refresh authentication.\n\n```javascript\n{\n    interceptNetworkError: true, // default: undefined\n}\n```\n\n## Examples\n\nThe [`examples/`](./examples) folder contains runnable examples that double as end-to-end tests:\n\n- **basic-refresh** — Core 401 → refresh → retry flow\n- **skip-auth-refresh** — `skipAuthRefresh` flag skips interception\n- **pause-instance** — `deduplicateRefresh` with concurrent requests\n- **custom-status-codes** — `statusCodes` + `shouldRefresh` callback\n- **on-retry-callback** — `onRetry` config mutation before retry\n- **network-error** — `interceptNetworkError` for CORS scenarios\n\nRun them all:\n\n```bash\nnpm run examples\n```\n\n---\n\n### Other usages of the library\n\nThis library has also been used for:\n\n- Automatic request throttling by [@amcsi](https://github.com/amcsi)\n- OTP challenges with Google2FA by [@LeoniePhiline](https://github.com/LeoniePhiline)\n\nhave you used it for something else? Create a PR with your use case to share it.\n\n---\n\n#### Want to help?\n\nCheck out [contribution guide](CONTRIBUTING.md) or my [patreon page!](https://www.patreon.com/dawidzbinski)\n","funding_links":["https://www.patreon.com/dawidzbinski"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflyrell%2Faxios-auth-refresh","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fflyrell%2Faxios-auth-refresh","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fflyrell%2Faxios-auth-refresh/lists"}