On session Expire , if any of the API fails then status code comes out to be 401 and we show prompt to ask password and re new the token again . But problem is that we do not want to show prompt we want react dialog to get open instead of that prompt.
Reason of using prompt was that prompt will make the app axios to wait for the password to enter and then it will move forward and will avoid failing of APIs coming next.
We have our code in app.axios file for prompting to ask password on session expire
app.axios.js file is below:-
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;