[Vuejs]-How to store JWT token properly using Laravel 5.4 and Vue.js 2

0👍

localStorage is not async so after login, you would need to refresh the entire page which is very bad UX to refresh single page app which I believe is what you develop since you use Vue.

What I can suggest instead is localForage which is nothing more than async localStorage. It is promise based and the syntax looks very similar to localStorage.

Example:

localforage.setItem(key, value, successCallback)
localforage.getItem('access_token', myCallback);

And to send the token in every request to backend you should use vue.http.interceptors.

Example:

Vue.http.interceptors.push((request, next)  => {
  request.headers['Authorization'] = auth.getAuthHeader()
    next((response) => {
      if(response.status == 401 ) {
        auth.logout();
        router.go('/login?unauthorized=1');
      }
   });
});

Read more on this in the Docs.

Leave a comment