axios-auto-refresh-jwt
v2.0.2
Published
Auto refresh jwt lib. Built with axios and jwt-decode.
Downloads
10
Readme
axios-auto-refresh-jwt
A package to auto refresh jwt tokens. Built with axios and jwt-decode.
installation
npm i axios-auto-refresh-jwt
usage
Let's start by importing:
import createHttp from 'axios-auto-refresh-jwt'
You must now pass an object with the following keys:
getTokens
: function that should return object with tokens, such as{ access: 'abc', refresh: 'abc' }
refreshEndpoint
: endpoint to refresh token and return a new access tokenheaderType
: the name that will be at the beginning of theAuthorization
in header, such as"Authorization": "<headerType> <access token>"
onRefreshed
: a callback for when the refresh token endpoint call is successfully made, this will be called by receiving aresponse
object returned by axios.onUnauthorized
: This will be called when the server responds with 401, for example, when the refresh token is expired, or when it is tampered with. This pass theerror
object as argument
complete example using localStorage
import createHttp from 'axios-auto-refresh-jwt'
import { baseURL, logoutRedirectUrl } from "app/settings";
import { removeTokens, getTokens, updateAccess } from "store/localStorage";
// the "store/localStorage" functions handle the tokens in localStorage.
// With redux, this can generate circular dependencies, so
// I recommend that you manipulate tokens directly in local|session storage or in cookies.
// remove tokens from localStorage, and redirect the user
const logoutUser = (error) => {
removeTokens();
window.location = logoutRedirectUrl;
};
const config = {
getTokens,
refreshEndpoint: "http://127.0.0.1:8000/api/auth/jwt/refresh",
headerType: "JWT",
onRefreshed: updateAccess,
onUnauthorized: logoutUser,
};
// create new instance and set up baseURL
// that's all!
const http = createHttp(config);
http.defaults.baseURL = baseURL;
export default http;
// some functions for example!
const refreshAccess = async (refresh) => {
const response = await http.post("api/auth/jwt/refresh", {
refresh,
});
return response;
};
const getUserInfo = async () => {
const response = await http.get("api/auth/users/me");
return response;
};
export { getUserInfo, refreshAccess };