M
M
Maxim Globak2018-07-18 00:22:37
JavaScript
Maxim Globak, 2018-07-18 00:22:37

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

2 answer(s)
A
Anton Spirin, 2018-07-18
@rockon404

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.

S
Sergiu Mitu, 2018-07-18
@EaGames

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: '',
....
}
}

on the client, when rendering the application, we check if there is a user in initialState and if there is, we automatically authorize him.
BUT there is not always access to the server, so you can do everything on the front too, that is, do NOT render anything until you check whether the user is authorized or not.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question