I am using React context for keeping the application state, JWT for auth, and React Router for routing.
The JWT has a hard expiry time of say 30 mins. I check for expiry every time the user visits a route, so if the token has expired before you go to the next route, you will be redirected to login. This works fine, but if the user is on some page and their token expires, and they make an API call while on the page, how would they get to know what is the problem? I can handle 401/403 in the response of every api call and based on that setState in the component which is using those API calls. But i would like to do this without each component trying to catch 401/403 and set state.
I am planning to write an axios interceptor for adding Auth Headers to outbound requests and to check AUTH errors on API responses. So i have an interceptor which checks if the response is 401 or 403.
This interceptor is outside of React code, which means it can't render any component directly or redirect the user to Login using React Router.
I have looked at similar questions and they do offer some workarounds, but none of them seem foolproof or a good way to do it.
React Router + Axios interceptors. How to Do a redirect?
How to redirect from axios interceptor with react Router V4?
- One of the suggestions is to setup the axios interceptor in your root component, so that it can set some state when 401/403 happens. I like this in terms of usability, but not in terms of code organization.
- People who use Redux can access the store outside of React, and use that to dispatch an action which leads the user to login page. I don't think that is possible when using React Context for state management.
- Other suggestions involde using window.location.href or using history.push, both of which seem to work in some way, but do not help with Redirecting the user to the same page after login.
I am trying to build a solution which works seamlessly with how React Router works with the App.For example React Router remembers the from location and i can use that to redirect user to the previous page after login, but if i use window.location.href = "/" or history.push('/'), then the user gets sent to the homepage, from where they are redirected to the login page, but now the previous page is the homepage, and not where the error happened. There seems to be no way for me to keep track of the previous location in the same way React Router does.