<code>import axios from "axios";
import store from "../redux/store/store";
import { updateLoaderState } from "../redux/actions/ui-state.action";
import { MESSAGES } from "../constants/messages";
import { APP_PAGES } from "../constants/app-pages";
import UserService from "../services/user.service";
import ClientService from "../services/client.service";
import AuthService from "../services/auth.service";
/**
* Component is configuring the request and response for axios.
*/
const appAxios = axios.create();
// to maintain the count of api calls, in case of multiple api calls, hide the loader only in case of last call
let activeRequestCount = 0;
// to maintain the promise of getting the new token
let refreshTokenPromise;
/**
* Configuring the request : Adding JWT token to the request header.
*/
appAxios.interceptors.request.use((req) => {
// show the loader before any API call
store.dispatch(updateLoaderState({ showLoader: true }));
activeRequestCount++;
const currentUser = UserService.getCurrentUser();
if (currentUser) {
req.headers['token'] = currentUser?.token;
}
req.headers['app-code'] = ClientService.getAppCode();
return req;
}, null, { synchronous: true });
/**
* Configuring the response received
*/
appAxios.interceptors.response.use(
(res) => {
activeRequestCount--;
// hide the loader after getting the response, only if it is the last api call
if (activeRequestCount === 0) {
store.dispatch(updateLoaderState({ showLoader: false }));
}
return res.data;
},
(err) => {
activeRequestCount = 0;
store.dispatch(updateLoaderState({ showLoader: false }));
if (err.response) {
// if from prompt of session expire , after filling password and hitting login api
// if any error comes then user is log out
// error may come in login page while login so we have check for location href also
// suppose user get error while login again then it will again comes to app axios then
// we will logout the user so location href check is their as we may get error while logging on login page
if (err.response.status === 401 && err.config.url.endsWith(APP_PAGES.LOGIN)
&& !window.location.href.endsWith(APP_PAGES.LOGIN)) {
// If the error originates from the login API and has a status code of 401,
// logout the user
AuthService.logout();
} else if (err.response.status === 401) {
// For other 401 errors (not from the login API), handle token refresh
if (!window.location.href.endsWith(APP_PAGES.LOGIN)) {
// check for an existing in-progress request
if (!refreshTokenPromise) {
// if nothing is in-progress, start a new refresh token request
// if session got expires then we prompt user for the password
// promise is triggered to login after prompt
// until the promise resolves other request waits for it
const password = prompt(MESSAGES.SESSION_EXPIRED);
if (password) {
const currentUser = UserService.getCurrentUser();
refreshTokenPromise = AuthService.login(currentUser?.email, password)
.then(user => {
// clear the promise state
refreshTokenPromise = null;
// resolve the promise with new token
return user?.token;
});
} else {
AuthService.logout();
}
}
// if on cancel of the prompt it is navigated to the login page and log out
// then no need for hitting failed request
if (!window.location.href.endsWith(APP_PAGES.LOGIN)) {
return refreshTokenPromise.then(token => {
// since our request gets once failed and also x-csrf token
// is reqd to verify if it is from trusted source and not malacious source
err.config.headers['X-CSRF-TOKEN'] = token;
return appAxios.request(err.config);
});
}
}
}
return Promise.reject(err);
}
throw err;
}
);
export default appAxios;
</code>
<code>import axios from "axios";
import store from "../redux/store/store";
import { updateLoaderState } from "../redux/actions/ui-state.action";
import { MESSAGES } from "../constants/messages";
import { APP_PAGES } from "../constants/app-pages";
import UserService from "../services/user.service";
import ClientService from "../services/client.service";
import AuthService from "../services/auth.service";
/**
* Component is configuring the request and response for axios.
*/
const appAxios = axios.create();
// to maintain the count of api calls, in case of multiple api calls, hide the loader only in case of last call
let activeRequestCount = 0;
// to maintain the promise of getting the new token
let refreshTokenPromise;
/**
* Configuring the request : Adding JWT token to the request header.
*/
appAxios.interceptors.request.use((req) => {
// show the loader before any API call
store.dispatch(updateLoaderState({ showLoader: true }));
activeRequestCount++;
const currentUser = UserService.getCurrentUser();
if (currentUser) {
req.headers['token'] = currentUser?.token;
}
req.headers['app-code'] = ClientService.getAppCode();
return req;
}, null, { synchronous: true });
/**
* Configuring the response received
*/
appAxios.interceptors.response.use(
(res) => {
activeRequestCount--;
// hide the loader after getting the response, only if it is the last api call
if (activeRequestCount === 0) {
store.dispatch(updateLoaderState({ showLoader: false }));
}
return res.data;
},
(err) => {
activeRequestCount = 0;
store.dispatch(updateLoaderState({ showLoader: false }));
if (err.response) {
// if from prompt of session expire , after filling password and hitting login api
// if any error comes then user is log out
// error may come in login page while login so we have check for location href also
// suppose user get error while login again then it will again comes to app axios then
// we will logout the user so location href check is their as we may get error while logging on login page
if (err.response.status === 401 && err.config.url.endsWith(APP_PAGES.LOGIN)
&& !window.location.href.endsWith(APP_PAGES.LOGIN)) {
// If the error originates from the login API and has a status code of 401,
// logout the user
AuthService.logout();
} else if (err.response.status === 401) {
// For other 401 errors (not from the login API), handle token refresh
if (!window.location.href.endsWith(APP_PAGES.LOGIN)) {
// check for an existing in-progress request
if (!refreshTokenPromise) {
// if nothing is in-progress, start a new refresh token request
// if session got expires then we prompt user for the password
// promise is triggered to login after prompt
// until the promise resolves other request waits for it
const password = prompt(MESSAGES.SESSION_EXPIRED);
if (password) {
const currentUser = UserService.getCurrentUser();
refreshTokenPromise = AuthService.login(currentUser?.email, password)
.then(user => {
// clear the promise state
refreshTokenPromise = null;
// resolve the promise with new token
return user?.token;
});
} else {
AuthService.logout();
}
}
// if on cancel of the prompt it is navigated to the login page and log out
// then no need for hitting failed request
if (!window.location.href.endsWith(APP_PAGES.LOGIN)) {
return refreshTokenPromise.then(token => {
// since our request gets once failed and also x-csrf token
// is reqd to verify if it is from trusted source and not malacious source
err.config.headers['X-CSRF-TOKEN'] = token;
return appAxios.request(err.config);
});
}
}
}
return Promise.reject(err);
}
throw err;
}
);
export default appAxios;
</code>
import axios from "axios";
import store from "../redux/store/store";
import { updateLoaderState } from "../redux/actions/ui-state.action";
import { MESSAGES } from "../constants/messages";
import { APP_PAGES } from "../constants/app-pages";
import UserService from "../services/user.service";
import ClientService from "../services/client.service";
import AuthService from "../services/auth.service";
/**
* Component is configuring the request and response for axios.
*/
const appAxios = axios.create();
// to maintain the count of api calls, in case of multiple api calls, hide the loader only in case of last call
let activeRequestCount = 0;
// to maintain the promise of getting the new token
let refreshTokenPromise;
/**
* Configuring the request : Adding JWT token to the request header.
*/
appAxios.interceptors.request.use((req) => {
// show the loader before any API call
store.dispatch(updateLoaderState({ showLoader: true }));
activeRequestCount++;
const currentUser = UserService.getCurrentUser();
if (currentUser) {
req.headers['token'] = currentUser?.token;
}
req.headers['app-code'] = ClientService.getAppCode();
return req;
}, null, { synchronous: true });
/**
* Configuring the response received
*/
appAxios.interceptors.response.use(
(res) => {
activeRequestCount--;
// hide the loader after getting the response, only if it is the last api call
if (activeRequestCount === 0) {
store.dispatch(updateLoaderState({ showLoader: false }));
}
return res.data;
},
(err) => {
activeRequestCount = 0;
store.dispatch(updateLoaderState({ showLoader: false }));
if (err.response) {
// if from prompt of session expire , after filling password and hitting login api
// if any error comes then user is log out
// error may come in login page while login so we have check for location href also
// suppose user get error while login again then it will again comes to app axios then
// we will logout the user so location href check is their as we may get error while logging on login page
if (err.response.status === 401 && err.config.url.endsWith(APP_PAGES.LOGIN)
&& !window.location.href.endsWith(APP_PAGES.LOGIN)) {
// If the error originates from the login API and has a status code of 401,
// logout the user
AuthService.logout();
} else if (err.response.status === 401) {
// For other 401 errors (not from the login API), handle token refresh
if (!window.location.href.endsWith(APP_PAGES.LOGIN)) {
// check for an existing in-progress request
if (!refreshTokenPromise) {
// if nothing is in-progress, start a new refresh token request
// if session got expires then we prompt user for the password
// promise is triggered to login after prompt
// until the promise resolves other request waits for it
const password = prompt(MESSAGES.SESSION_EXPIRED);
if (password) {
const currentUser = UserService.getCurrentUser();
refreshTokenPromise = AuthService.login(currentUser?.email, password)
.then(user => {
// clear the promise state
refreshTokenPromise = null;
// resolve the promise with new token
return user?.token;
});
} else {
AuthService.logout();
}
}
// if on cancel of the prompt it is navigated to the login page and log out
// then no need for hitting failed request
if (!window.location.href.endsWith(APP_PAGES.LOGIN)) {
return refreshTokenPromise.then(token => {
// since our request gets once failed and also x-csrf token
// is reqd to verify if it is from trusted source and not malacious source
err.config.headers['X-CSRF-TOKEN'] = token;
return appAxios.request(err.config);
});
}
}
}
return Promise.reject(err);
}
throw err;
}
);
export default appAxios;
I am having app.axios.js file in which on 401 status code we have session expire and we prompt to enter password and after that we re generate the token from that password and token gets renewed.
I am just using simple prompt and ask for password to login and then we resolve the promise . How to use react dialog to in app.axios.js or from some other component and in the meanwhile promise should not get resolved until we fill the password.