0

I want to know how to keep user logged in all the time, so that when his token about to expire he could refresh it and would not receive 401 status when entering guarded routes and so that his data could be reflected on page whenever he refreshed it.

My assumption is that once App.vue is opened it should fetch data from server, confirming that user is logged and requesting user data, and eventually storing it in Vuex or localStorage. Hope I am on the right way to solution

fetch('http://localhost:9000/api/refresh',{
            method:'POST',
            mode:'cors',
            body:JSON.stringify({refreshToken :localStorage.getItem('refreshToken')}),
            headers:{'Content-Type':'application/json'}
        }
        ).then(res=>{
            if(res.status===200){
                return res.json()
            }
            else return
        })
        .then(({token})=>{localStorage.setItem('token',token)
        Store.dispatch('authorize',JSON.parse(localStorage.getItem('user')))
        return })
jps
  • 20,041
  • 15
  • 75
  • 79
  • Yep, the idea is good. You're just missing a middleware checking that every time a page is loaded, the user have access to it. If he doesn't (401 error), send a refresh HTTP call. If it fails, redirect the user to the login page. – kissu May 23 '22 at 13:48
  • Yep! Thats how I did it. I am fetching data and in case I have 401 I make an attempt to Refresh token and if there another error I am redirected to login page or wherever. Another thing is that where is it better to store userdata? Localstorage or directly in Vuex? Thank you for your answer buddy! – vladissick May 23 '22 at 16:42
  • Usually, your store the data of the user in Vuex because it's reactive and easier to work with. Your store a JWT token in localStorage or small pieces of data. Even if a cookie is safer for that purpose. – kissu May 23 '22 at 16:45

0 Answers0