{"id":20114358,"url":"https://github.com/jetbridge/axios-jwt","last_synced_at":"2025-04-05T10:07:32.192Z","repository":{"id":34931549,"uuid":"191525541","full_name":"jetbridge/axios-jwt","owner":"jetbridge","description":"Store, transmit, refresh JWT authentication tokens for axios","archived":false,"fork":false,"pushed_at":"2024-04-24T16:18:49.000Z","size":1862,"stargazers_count":112,"open_issues_count":16,"forks_count":30,"subscribers_count":10,"default_branch":"master","last_synced_at":"2024-05-02T00:28:56.665Z","etag":null,"topics":["axios","interceptor","jwt","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/axios-jwt/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/jetbridge.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"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":"2019-06-12T08:00:42.000Z","updated_at":"2024-06-07T23:29:23.867Z","dependencies_parsed_at":"2024-02-08T04:29:12.888Z","dependency_job_id":"896db5fc-9974-4461-81dc-27db959ed3e7","html_url":"https://github.com/jetbridge/axios-jwt","commit_stats":{"total_commits":69,"total_committers":12,"mean_commits":5.75,"dds":0.7246376811594203,"last_synced_commit":"14d6abcc726718ec24a3ed1119acdff7b86fe125"},"previous_names":[],"tags_count":23,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetbridge%2Faxios-jwt","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetbridge%2Faxios-jwt/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetbridge%2Faxios-jwt/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/jetbridge%2Faxios-jwt/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/jetbridge","download_url":"https://codeload.github.com/jetbridge/axios-jwt/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247318744,"owners_count":20919484,"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":["axios","interceptor","jwt","typescript"],"created_at":"2024-11-13T18:29:29.188Z","updated_at":"2025-04-05T10:07:32.168Z","avatar_url":"https://github.com/jetbridge.png","language":"TypeScript","readme":"# axios-jwt\n\nStore, clear, transmit and automatically refresh JWT authentication tokens. This library can be used in both web and react-native projects.\n\n## What does it do?\n\nApplies a request interceptor to your axios instance.\n\nThe interceptor automatically adds an access token header (default: `Authorization`) to all requests.\nIt stores `accessToken` and `refreshToken` in `localStorage` (web) or 'AsyncStorage' (React Native) and reads them when needed.\n\nIt parses the expiration time of your access token and checks to see if it is expired before every request. If it has expired, a request to\nrefresh and store a new access token is automatically performed before the request proceeds.\n\n## Installation instructions\n\n### Install axios-jwt\n\n```bash\nnpm install --save axios-jwt # or `yarn add axios-jwt`\n```\n\n### Additional steps for React Native projects\n\nYou will also need to install react-native-async-storage in order to be able to store and retrieve tokens.\n\n#### Expo\n\n```bash\nexpo install @react-native-async-storage/async-storage\n```\n\n### React Native\n\n```bash\nnpm install --save @react-native-async-storage/async-storage # or `yarn add @react-native-async-storage/async-storage`\nnpx pod-install # installs the native iOS packages\n```\n\n## How do I use it?\n\n1. Create an axios instance\n2. Define a token refresh function\n3. Configure the interceptor\n4. Store tokens on login with `setAuthTokens()`\n5. Clear tokens on logout with `clearAuthTokens()`\n\n### Applying the interceptor\n\n```typescript\n// api.ts\n\nimport { IAuthTokens, TokenRefreshRequest, applyAuthTokenInterceptor, getBrowserLocalStorage } from 'axios-jwt'\nimport axios from 'axios'\n\nconst BASE_URL = 'https://api.example.com'\n\n// 1. Create an axios instance that you wish to apply the interceptor to\nexport const axiosInstance = axios.create({ baseURL: BASE_URL })\n\n// 2. Define token refresh function.\nconst requestRefresh: TokenRefreshRequest = async (refreshToken: string): Promise\u003cIAuthTokens | string\u003e =\u003e {\n\n  // Important! Do NOT use the axios instance that you supplied to applyAuthTokenInterceptor (in our case 'axiosInstance')\n  // because this will result in an infinite loop when trying to refresh the token.\n  // Use the global axios client or a different instance\n  const response = await axios.post(`${BASE_URL}/auth/refresh_token`, { token: refreshToken })\n\n  // If your backend supports rotating refresh tokens, you may also choose to return an object containing both tokens:\n  // return {\n  //  accessToken: response.data.access_token,\n  //  refreshToken: response.data.refresh_token\n  //}\n\n  return response.data.access_token\n}\n\n// 3. Add interceptor to your axios instance\napplyAuthTokenInterceptor(axiosInstance, { requestRefresh })\n\n// New to 2.2.0+: initialize with storage: localStorage/sessionStorage/nativeStorage. Helpers: getBrowserLocalStorage, getBrowserSessionStorage\nconst getStorage = getBrowserLocalStorage\n\n// You can create you own storage, it has to comply with type StorageType\napplyAuthTokenInterceptor(axiosInstance, { requestRefresh, getStorage })\n```\n\n### Login/logout\n\n```typescript\n// login.ts\n\nimport { isLoggedIn, setAuthTokens, clearAuthTokens, getAccessToken, getRefreshToken } from 'axios-jwt'\nimport { axiosInstance } from './api'\n\n// 4. Post email and password and get tokens in return. Call setAuthTokens with the result.\nconst login = async (params: ILoginRequest) =\u003e {\n  const response = await axiosInstance.post('/auth/login', params)\n\n  // save tokens to storage\n  setAuthTokens({\n    accessToken: response.data.access_token,\n    refreshToken: response.data.refresh_token\n  })\n}\n\n// 5. Remove the auth tokens from storage\nconst logout = async () =\u003e await clearAuthTokens()\n\n// Check if refresh token exists\nif (await isLoggedIn()) {\n  // assume we are logged in because we have a refresh token\n}\n\n// Get access to tokens\nconst accessToken = await getAccessToken()\nconst refreshToken = await getRefreshToken()\n```\n\n## Configuration\n\n```typescript\napplyAuthTokenInterceptor(axiosInstance, {\n  requestRefresh,  // async function that takes a refreshToken and returns a promise the resolves in a fresh accessToken\n  header: \"Authorization\",  // header name\n  headerPrefix: \"Bearer \",  // header value prefix\n})\n```\n\n## Caveats\n\n- Your backend should allow a few seconds of leeway between when the token expires and when it actually becomes unusable.\n\n## Non-TypeScript implementation\n\n```javascript\nimport { applyAuthTokenInterceptor, setAuthTokens, clearAuthTokens } from 'axios-jwt';\nimport axios from 'axios';\n\nconst BASE_URL = 'https://api.example.com'\n\n// 1. Create an axios instance that you wish to apply the interceptor to\nconst axiosInstance = axios.create({ baseURL: BASE_URL })\n\n// 2. Define token refresh function.\nconst requestRefresh = (refresh) =\u003e {\n    // Notice that this is the global axios instance, not the axiosInstance!  \u003c-- important\n    return axios.post(`${BASE_URL}/auth/refresh_token`, { refresh })\n      .then(response =\u003e response.data.access_token)\n};\n\n// 3. Apply interceptor\napplyAuthTokenInterceptor(axiosInstance, { requestRefresh });  // Notice that this uses the axiosInstance instance.  \u003c-- important\n\n// 4. Logging in\nconst login = async (params) =\u003e {\n  const response = await axiosInstance.post('/auth/login', params)\n\n  // save tokens to storage\n  setAuthTokens({\n    accessToken: response.data.access_token,\n    refreshToken: response.data.refresh_token\n  })\n}\n\n// 5. Logging out\nconst logout = () =\u003e clearAuthTokens()\n\n// Now just make all requests using your axiosInstance instance\naxiosInstance.get('/api/endpoint/that/requires/login').then(response =\u003e { })\n\n```\n","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjetbridge%2Faxios-jwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjetbridge%2Faxios-jwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjetbridge%2Faxios-jwt/lists"}