Vuex state on page refresh

Vuex state is kept in memory. Page load will purge this current state. This is why the state does not persist on reload.

But the vuex-persistedstate plugin solves this issue

npm install --save vuex-persistedstate

Now import this into the store.

import Vue from 'vue'
import Vuex from 'vuex'
import account from './modules/account'
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    account,
  },
  plugins: [createPersistedState()]
});

It worked perfectly with a single line of code: plugins: [createPersistedState()]


When creating your VueX state, save it to session storage using the vuex-persistedstate plugin. In this way, the information will be lost when the browser is closed. Avoid use of cookies as these values will travel between client and server.

import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from 'vuex-persistedstate'

Vue.use(Vuex);

export default new Vuex.Store({
    plugins: [createPersistedState({
        storage: window.sessionStorage,
    })],
    state: {
        //....
    }
});

Use sessionStorage.clear(); when user logs out manually.

EDIT: Note that if your store have values that are not intrinsically string types (eg dates), your application may fail or behaviour may change because the serialisation/deserialisation process will convert these values to strings.


This is a known use case. There are different solutions.

For example, one can use vuex-persistedstate. This is a plugin for vuex to handle and store state between page refreshes.

Sample code:

import { Store } from 'vuex'
import createPersistedState from 'vuex-persistedstate'
import * as Cookies from 'js-cookie'

const store = new Store({
  // ...
  plugins: [
    createPersistedState({
      getState: (key) => Cookies.getJSON(key),
      setState: (key, state) => Cookies.set(key, state, { expires: 3, secure: true })
    })
  ]
})

What we do here is simple:

  1. you need to install js-cookie
  2. on getState we try to load saved state from Cookies
  3. on setState we save our state to Cookies

Docs and installation instructions: https://www.npmjs.com/package/vuex-persistedstate