MostafaGamal's avatar

What is the best practice to persist auth user info in SPA?

What is the best practice to persist auth user info in SPA? Is it a good practice to store it in local storage( i.g. localStorage.getItem('authUser') ), or widow object ( i.g. window.user) ? Should I send a request to the server every time I want to access the auth user info instead of persisting it in local storage?

0 likes
3 replies
Spiral's avatar

You can make a helper in vue

 // Setting bearer token for the api calls
    setUser(user) {

        localStorage.removeItem('getUser');

        localStorage.setItem('getUser', user); // store the token in localstorage
    },// Setting bearer token for the api calls
    setUserId(id) {

        localStorage.removeItem('getUserId');

        localStorage.setItem('getUserId', id); // store the token in localstorage
    },
    setRole(role) {

        localStorage.removeItem('getRole');

        localStorage.setItem('getRole', role); // store the token in localstorage
    },

and You can use in a component when logged in the user

axios.post('/api/login', this.$data)
				.then(res => {
                        this.setUser(res.data.data.access_token);
                        axios.defaults.headers.common['Authorization'] = localStorage.getItem('getUser')
                        this.setUserId(res.data.data.user.id);
                        this.setProfileImage(res.data.data.user.image);
                        this.setRole(res.data.data.role);
                        this.$router.push('/dashboard')
				})
				.catch(error => {
					this.errors = error.response.data.msg;
				})
MostafaGamal's avatar

@spiral Thank you for your answer, but I'm not asking about the way to store the user in local storage, I want to know whether storing it in local storage is a good practice from the security point of view. Should I send a server request every time I want to access the user?

trin's avatar

localstorage good choice.

  • u save token in localstorage, when user auth
  • u check token, when app start (send query for userinfo with token)
  • u add header like “x-token” for all xhr query, if token good.

Please or to participate in this conversation.