Amit Teli Amit Teli - 9 days ago 8
React JSX Question

Howto redirect from axios interceptor in reactjs app?

I am trying to check each axios request for presence of token inside the header for non-public paths. I want to take the user to login page in case token is not found.
But this is inside reactjs app. What is the way to make this happen?

axios.interceptors.request.use(function (config) {
//If the header does not contain the token and the url not public, redirect to login
var accessToken = null;
if(sessionStorage.getItem('currentUserString')){
accessToken = 'bearer '+JSON.parse(sessionStorage.getItem('currentUserString')).tokenDetails.accessToken;
}

var configURL = config.url;
//if token is found add it to the header
if (accessToken) {
if (config.method !== 'OPTIONS') {
config.headers.authorization = accessToken;
}
}
//otherwise if the request is not for login page/auth service/home redirect to login page
else if(!isNotOpenPath(config.url)){

//we may want to store current path in the cookies. This can be retrieved after login is successful
//WHAT TO DO HERE TO TAKE USER TO LOGIN PAGE IN THE REACT JS APP????
}
}


How to signal react app, particularly we don't have dispatch here.
Can I just use
document.location.href='\login'
?

Answer

I think the way to have routes inside your app is using React Router... Then to navigate you could try this...

https://github.com/ReactTraining/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md

Comments