Installations
npm install axios-jwt
Developer
Developer Guide
Module System
CommonJS
Min. Node Version
Typescript Support
Yes
Node Version
20.10.0
NPM Version
10.2.3
Statistics
117 Stars
90 Commits
30 Forks
10 Watching
7 Branches
16 Contributors
Updated on 04 Nov 2024
Languages
TypeScript (99.03%)
JavaScript (0.97%)
Total Downloads
Cumulative downloads
Total Downloads
509,350
Last day
21.7%
601
Compared to previous day
Last week
51.6%
4,675
Compared to previous week
Last month
26.4%
17,239
Compared to previous month
Last year
145%
268,643
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
2
Peer Dependencies
2
axios-jwt
Store, clear, transmit and automatically refresh JWT authentication tokens. This library can be used in both web and react-native projects.
What does it do?
Applies a request interceptor to your axios instance.
The interceptor automatically adds an access token header (default: Authorization
) to all requests.
It stores accessToken
and refreshToken
in localStorage
(web) or 'AsyncStorage' (React Native) and reads them when needed.
It 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 refresh and store a new access token is automatically performed before the request proceeds.
Installation instructions
Install axios-jwt
1npm install --save axios-jwt # or `yarn add axios-jwt`
Additional steps for React Native projects
You will also need to install react-native-async-storage in order to be able to store and retrieve tokens.
Expo
1expo install @react-native-async-storage/async-storage
React Native
1npm install --save @react-native-async-storage/async-storage # or `yarn add @react-native-async-storage/async-storage` 2npx pod-install # installs the native iOS packages
How do I use it?
- Create an axios instance
- Define a token refresh function
- Configure the interceptor
- Store tokens on login with
setAuthTokens()
- Clear tokens on logout with
clearAuthTokens()
Applying the interceptor
1// api.ts 2 3import { IAuthTokens, TokenRefreshRequest, applyAuthTokenInterceptor, getBrowserLocalStorage } from 'axios-jwt' 4import axios from 'axios' 5 6const BASE_URL = 'https://api.example.com' 7 8// 1. Create an axios instance that you wish to apply the interceptor to 9export const axiosInstance = axios.create({ baseURL: BASE_URL }) 10 11// 2. Define token refresh function. 12const requestRefresh: TokenRefreshRequest = async (refreshToken: string): Promise<IAuthTokens | string> => { 13 14 // Important! Do NOT use the axios instance that you supplied to applyAuthTokenInterceptor (in our case 'axiosInstance') 15 // because this will result in an infinite loop when trying to refresh the token. 16 // Use the global axios client or a different instance 17 const response = await axios.post(`${BASE_URL}/auth/refresh_token`, { token: refreshToken }) 18 19 // If your backend supports rotating refresh tokens, you may also choose to return an object containing both tokens: 20 // return { 21 // accessToken: response.data.access_token, 22 // refreshToken: response.data.refresh_token 23 //} 24 25 return response.data.access_token 26} 27 28// 3. Add interceptor to your axios instance 29applyAuthTokenInterceptor(axiosInstance, { requestRefresh }) 30 31// New to 2.2.0+: initialize with storage: localStorage/sessionStorage/nativeStorage. Helpers: getBrowserLocalStorage, getBrowserSessionStorage 32const getStorage = getBrowserLocalStorage 33 34// You can create you own storage, it has to comply with type StorageType 35applyAuthTokenInterceptor(axiosInstance, { requestRefresh, getStorage })
Login/logout
1// login.ts 2 3import { isLoggedIn, setAuthTokens, clearAuthTokens, getAccessToken, getRefreshToken } from 'axios-jwt' 4import { axiosInstance } from './api' 5 6// 4. Post email and password and get tokens in return. Call setAuthTokens with the result. 7const login = async (params: ILoginRequest) => { 8 const response = await axiosInstance.post('/auth/login', params) 9 10 // save tokens to storage 11 setAuthTokens({ 12 accessToken: response.data.access_token, 13 refreshToken: response.data.refresh_token 14 }) 15} 16 17// 5. Remove the auth tokens from storage 18const logout = async () => await clearAuthTokens() 19 20// Check if refresh token exists 21if (await isLoggedIn()) { 22 // assume we are logged in because we have a refresh token 23} 24 25// Get access to tokens 26const accessToken = await getAccessToken() 27const refreshToken = await getRefreshToken()
Configuration
1applyAuthTokenInterceptor(axiosInstance, { 2 requestRefresh, // async function that takes a refreshToken and returns a promise the resolves in a fresh accessToken 3 header: "Authorization", // header name 4 headerPrefix: "Bearer ", // header value prefix 5})
Caveats
- Your backend should allow a few seconds of leeway between when the token expires and when it actually becomes unusable.
Non-TypeScript implementation
1import { applyAuthTokenInterceptor, setAuthTokens, clearAuthTokens } from 'axios-jwt'; 2import axios from 'axios'; 3 4const BASE_URL = 'https://api.example.com' 5 6// 1. Create an axios instance that you wish to apply the interceptor to 7const axiosInstance = axios.create({ baseURL: BASE_URL }) 8 9// 2. Define token refresh function. 10const requestRefresh = (refresh) => { 11 // Notice that this is the global axios instance, not the axiosInstance! <-- important 12 return axios.post(`${BASE_URL}/auth/refresh_token`, { refresh }) 13 .then(response => response.data.access_token) 14}; 15 16// 3. Apply interceptor 17applyAuthTokenInterceptor(axiosInstance, { requestRefresh }); // Notice that this uses the axiosInstance instance. <-- important 18 19// 4. Logging in 20const login = async (params) => { 21 const response = await axiosInstance.post('/auth/login', params) 22 23 // save tokens to storage 24 setAuthTokens({ 25 accessToken: response.data.access_token, 26 refreshToken: response.data.refresh_token 27 }) 28} 29 30// 5. Logging out 31const logout = () => clearAuthTokens() 32 33// Now just make all requests using your axiosInstance instance 34axiosInstance.get('/api/endpoint/that/requires/login').then(response => { }) 35
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
Found 12/26 approved changesets -- score normalized to 4
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
- Warn: no topLevel permission defined: .github/workflows/push.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/push.yml:9: update your workflow using https://app.stepsecurity.io/secureworkflow/jetbridge/axios-jwt/push.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/push.yml:10: update your workflow using https://app.stepsecurity.io/secureworkflow/jetbridge/axios-jwt/push.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/push.yml:27: update your workflow using https://app.stepsecurity.io/secureworkflow/jetbridge/axios-jwt/push.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/push.yml:28: update your workflow using https://app.stepsecurity.io/secureworkflow/jetbridge/axios-jwt/push.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/push.yml:43: update your workflow using https://app.stepsecurity.io/secureworkflow/jetbridge/axios-jwt/push.yml/master?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/push.yml:44: update your workflow using https://app.stepsecurity.io/secureworkflow/jetbridge/axios-jwt/push.yml/master?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/push.yml:17
- Warn: npmCommand not pinned by hash: .github/workflows/push.yml:17
- Warn: npmCommand not pinned by hash: .github/workflows/push.yml:35
- Warn: npmCommand not pinned by hash: .github/workflows/push.yml:35
- Warn: npmCommand not pinned by hash: .github/workflows/push.yml:51
- Warn: npmCommand not pinned by hash: .github/workflows/push.yml:51
- Info: 0 out of 6 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 6 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
license file not detected
Details
- Warn: project does not have a license file
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 16 are checked with a SAST tool
Reason
18 existing vulnerabilities detected
Details
- Warn: Project is vulnerable to: GHSA-67hx-6x53-jw92
- Warn: Project is vulnerable to: GHSA-wf5p-g6vw-rhxx
- Warn: Project is vulnerable to: GHSA-8hc4-vh64-cxmj
- Warn: Project is vulnerable to: GHSA-grv7-fg5c-xmjg
- Warn: Project is vulnerable to: GHSA-3xgq-45jj-v275
- Warn: Project is vulnerable to: GHSA-6w63-h3fj-q4vw
- Warn: Project is vulnerable to: GHSA-jchw-25xp-jwwc
- Warn: Project is vulnerable to: GHSA-cxjh-pqwp-8mfp
- Warn: Project is vulnerable to: GHSA-78xj-cgh5-2h22
- Warn: Project is vulnerable to: GHSA-2p57-rm9w-gvfp
- Warn: Project is vulnerable to: GHSA-952p-6rrq-rcjv
- Warn: Project is vulnerable to: GHSA-rxrc-rgv4-jpvx
- Warn: Project is vulnerable to: GHSA-c2qf-rxjj-qqgw
- Warn: Project is vulnerable to: GHSA-m6fv-jmcg-4jfg
- Warn: Project is vulnerable to: GHSA-cm22-4g7w-348p
- Warn: Project is vulnerable to: GHSA-72xf-g2v4-qvf3
- Warn: Project is vulnerable to: GHSA-j8xg-fqg3-53r7
- Warn: Project is vulnerable to: GHSA-3h5v-q93c-6h6q
Score
2.6
/10
Last Scanned on 2024-11-18
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 MoreOther packages similar to axios-jwt
vue-axios-jwt
Vue plugin for axios-jwt
@vueuse/integrations
Integration wrappers for utility libraries
axios
Promise based HTTP client for the browser and node.js
react-native-axios-jwt
Axios interceptor to store, transmit, clear and automatically refresh tokens for authentication in a React Native environment