Reputation: 138
So, this may seem like a very simple question. And I have researched with Stackoverflow to see is someone has the same kind of question. I could not find any.
I am using React
, and a NodeJS
backend. Using redux, I want to ensure that on every page load that it checks to see if the user is logged in. I am doing this:
`useEffect(() => {
store.dispatch(loadUser());
}, []);`
the load user in Redux is:
export const loadUser = () => async (dispatch) => {
try {
const res = await axios.get('/auth/me');
dispatch({
type: USER_LOADED,
payload: res.data,
});
} catch (error) {
dispatch({
type: AUTH_ERROR,
});
}
};
So every time the application loads it loads the user into state.
When the user is not logged in however, I get an message in the console:
I know why I am getting the error, the route in Nodejs is protected.
Obviously, I don't want the user to see this when the page is deployed. How would I handle this error properly?
Upvotes: 0
Views: 801
Reputation: 16309
There are two possible cases to consider:
The user directly navigates to a protected url while not being authenticated. In this case your backend knows the api requests it will try to make will fail when your react app renders the content of that route. Instead it should redirect (302 Found
) to the login route (which will let your react app render the login form instead of the original page he requested) where no api requests are made that require authentication.
The user hits an api endpoint without being authenticated. In that case your backend should respond with 401 Unauthorized
. Your react app should catch that and render the login form.
You should always assume that the user might perform an unauthorized request at any time and gracefully handle that.
So what you need to handle both cases is:
Two routes that serve your app. One is the login route that just serves your app. The other one is also just serving the app but only if the user is authenticated. Otherwise it should redirect to the login route. I'm assuming that your react app will only render the login form when first mounting on the login route where no api request happen that require authentication.
A handler in your react app that re-directs to/renders your login form in case an API request failed with 401
.
Upvotes: 1
Reputation: 2477
An easy way is to use local storage api. So, when someone logs in you should generate some kind of auth token and save it in local storage:
localStorage.setItem("token",TOKEN_VALUE)
then in your react app check if this value exist or not using:
localStorage.getItem("token")
if it exists then the user is still logged in and otherwise if not
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
This also will achieve a great user experience as they won't need to sign in everytime and they won't be logged out unless they want
Upvotes: 1