How to persist Vuex state

Persisting Vuex state ensures your application maintains user data and preferences across browser sessions and page reloads. As the creator of CoreUI with 25 years of development experience, I’ve implemented state persistence in numerous Vue.js enterprise applications. The most reliable approach uses the vuex-persistedstate plugin combined with localStorage for automatic state hydration and persistence. This method provides seamless user experience while maintaining application performance.

Use vuex-persistedstate plugin to automatically persist and restore Vuex state from localStorage.

// Install: npm install vuex-persistedstate

// store/index.js
import { createStore } from 'vuex'
import createPersistedState from 'vuex-persistedstate'

const store = createStore({
  state: {
    user: null,
    cart: [],
    preferences: {
      theme: 'light',
      language: 'en'
    }
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    ADD_TO_CART(state, item) {
      state.cart.push(item)
    },
    SET_THEME(state, theme) {
      state.preferences.theme = theme
    }
  },
  plugins: [
    createPersistedState({
      paths: ['user', 'cart', 'preferences']
    })
  ]
})

export default store

The vuex-persistedstate plugin automatically saves specified state paths to localStorage on every mutation and restores them when the store is created. The paths option allows selective persistence of state modules, preventing sensitive data from being stored locally. The plugin handles serialization and deserialization transparently.

Best Practice Note:

This is the same state persistence strategy we implement in CoreUI Vue applications for reliable user experience. Consider using sessionStorage for temporary data and implement state encryption for sensitive information that needs persistence.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team