[Vuejs]-Vuex persist authenticated status

1👍

Assuming you’re getting back a token from your API, you could store this in the local storage.

state: {
    authenticated: false,
    user: null,
    token: localStorage.getItem('token') || '',
},
actions:{
    await axios.post('/api/login', credentials).then(response => {
        const token = response.data.token
        localStorage.setItem('token', token)
    })
}

You could handle an expired token via Axios interceptors:

created () {
    this.$axios.interceptors.response.use(undefined, function (err) {
        return new Promise(function (resolve, reject) {
        if (err.status === 401) {
          this.$store.dispatch(logout)
        }
        throw err;
      });
    });
}

Vuex logout action

logout({commit}){
  return new Promise((resolve, reject) => {
    commit('logout')
    localStorage.removeItem('token')
    delete axios.defaults.headers.common['Authorization']
    resolve()
  })
}

2👍

There are two possible options to persist data: you could use cookies or local storage. Both options are frequently used, for example by Nuxt Auth.

An easy option to persist the store would be to use vuex-persist. You can find the getting started guide here.

0👍

@studio-pj. I don’t think it is safe to store a token in LocalStorage because it are user credentials.
Everywhere i read about LocalStorage is that it shouldn’t be used for login credentials and other security sensitive data.

Leave a comment