{"id":13810535,"url":"https://github.com/Flyrell/axios-auth-refresh","last_synced_at":"2025-05-14T10:33:50.961Z","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":1091,"open_issues_count":30,"forks_count":92,"subscribers_count":9,"default_branch":"master","last_synced_at":"2025-05-14T06:25:53.924Z","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-05-13T05:18:16.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":254120182,"owners_count":22017954,"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-08-04T02:00:58.211Z","updated_at":"2025-05-14T10:33:50.912Z","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\n:warning: Because of the bug [axios#2295](https://github.com/axios/axios/issues/2295) v0.19.0 is not supported. :warning:\n\n:white_check_mark: This has been fixed and will be released in axios v0.19.1\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 specify multiple status codes that you want the interceptor to run for.\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#### Pause the instance while \"refresh logic\" is running\n\nWhile your refresh logic is running, the interceptor will be triggered for every request\nwhich returns one of the `options.statusCodes` specified (HTTP 401 by default).\n\nIn order to prevent the interceptors loop (when your refresh logic fails with any of the status\ncodes specified in `options.statusCodes`) you need to use a [`skipAuthRefresh`](#skipping-the-interceptor)\nflag on your refreshing call inside the `refreshAuthLogic` function.\n\nIn case your refresh logic does not make any calls, you should consider using the following flag\nwhen initializing the interceptor to pause the whole axios instance while the refreshing is pending.\nThis prevents interceptor from running for each failed request.\n\n```javascript\n{\n    pauseInstanceWhileRefreshing: true, // default: false\n}\n```\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### 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### Changelog\n\n-   **v3.1.0**\n\n    -   axios v0.21.1 support\n    -   `interceptNetworkError` option introduced. See [#133](https://github.com/Flyrell/axios-auth-refresh/issues/133).\n\n-   **v3.0.0**\n    -   `skipWhileRefresh` flag has been deprecated due to its unclear name and its logic has been moved to `pauseInstanceWhileRefreshing` flag\n    -   `pauseInstanceWhileRefreshing` is set to `false` by default\n\n---\n\n#### Want to help?\n\nCheck out [contribution guide](CONTRIBUTING.md) or my [patreon page!](https://www.patreon.com/dawidzbinski)\n\n---\n\n#### Special thanks to [JetBrains](https://www.jetbrains.com/?from=axios-auth-refresh) for providing the IDE for our library\n\n\u003ca href=\"https://www.jetbrains.com/?from=axios-auth-refresh\" title=\"Link to JetBrains\"\u003e\u003cimg src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/1/1a/JetBrains_Logo_2016.svg/128px-JetBrains_Logo_2016.svg.png\" alt=\"JetBrains\"\u003e\u003c/a\u003e\n","funding_links":["https://www.patreon.com/dawidzbinski"],"categories":["TypeScript"],"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"}