Answer the question
In order to leave comments, you need to log in
How to store user data on the client?
Good afternoon! Please tell me the flow of storing user data on the client side. I'm doing a pet project and I'm a complete zero on the web. But my authorization flow looks like this.
During login, I climb to the API and authorize the user, i.e. I give him two JWT tokens (access & refresh) and save them to localstorage.
Then I immediately go after the user's data to use it on the site (name, email, access level) and save it in state.
On all internal pages I check the presence of a user to access the page. If there is no data, then I redirect to the login page.
Everything works well until the page is refreshed, then the state is cleared and there is no data, the user is redirected to the login page, which is not good.
1) Do I need to follow the user in the api in the root component, if there is none in the state?
2) What is considered a proof of user authorization? tokens or user data?
PS for each request to the api there is a check for the validity of the token and the processing of 401 errors.
Answer the question
In order to leave comments, you need to log in
1. Create an async action init(), where you load all the data necessary for initialization, or pass the token in the cookie, check and write the data on the server to the template:
2. On the client, for verification, you can use any data from the store (store.user, srore.auth, etc), of course, in the case of 401, the data in the store must be immediately updated and sent to Login.
In principle, you are doing everything right. As for the refresh, it's best to check if the user is authorized on the server for this instead of localstorage, it's better to use cookies, since they can be accessed from the server. We check if there is a token cookie and it is valid, we render the site with the so-called initialState, for example:
window.initialState = {
user: {
id: 1,
avatar: '',
....
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question