Wavesenterprise JWT refresh library for both Node.js and browser.
Installation
npm install @wavesenterprise/api-token-refresher --save
npm install axios@0.21.4
Example of usage
config
type TokenPair = {
access_token: string,
refresh_token: string,
}
export type TokenRefresherConfig = {
authorization: TokenPair, // inital auth pair
refreshCallback(refreshToken: string): Promise<TokenPair>, // called to get new TokenPair
axiosRequestConfig?: AxiosRequestConfig, // optional, custom AxiosRequestConfig
onChangeAccessToken?(token: string): void, // optional, called after success token refresh
onRefreshFailed?(err: any): void, // optional, default console.log(err), called in case refresh error
refreshBeforeExpire?: number, // optional, default 30000, refresh will start if expiration - refreshBeforeExpire < Date.now()
minTimeBeforeExpireToSendReq?: number, // optional, default 1000, if expiration - minTimeBeforeExpireToSendReq < Date.now() token will be updted synchronously before req
maxAttemptsToRefreshToken?: number, // optional, default 5
sleepAfterError?: number, // optional default 1000
}
Usage
Full example can be found in examples/
folder
import { ApiTokenRefresher } from '@wavesenterprise/api-token-refresher'
import axios from 'axios'
const refreshCallback = async (token: string) => {
return Promise.reject('just test')
try {
const { data } = await axios.post(`${AUTH_SERVICE_ADDRESS}/v1/auth/refresh`, { token })
console.log('token refreshed')
return data
} catch (e) {
console.log('refresh failed relogin')
return getTokens()
}
}
const apiTokenRefresher = new ApiTokenRefresher({
authorization: tokens,
refreshCallback,
})
const { axios } = apiTokenRefresher.init()