How to persist Vuex state
Persisting Vuex state ensures that application data survives browser refreshes and maintains user experience across sessions in Vue applications. With over 25 years of experience building complex applications and as the creator of CoreUI, I’ve implemented state persistence for numerous production Vue applications. The most effective approach is using Vuex plugins with localStorage or sessionStorage to automatically save and restore state data. This provides seamless data persistence with configurable storage options and proper error handling for different browser environments.
Use Vuex plugins with localStorage to automatically persist and restore state data across browser sessions and page refreshes.
// store/plugins/persistence.js
const createPersistedState = (options = {}) => {
const {
key = 'vuex-state',
paths = [],
storage = localStorage,
reducer = state => state
} = options
return store => {
// Restore state on initialization
try {
const savedState = JSON.parse(storage.getItem(key))
if (savedState) {
store.replaceState({
...store.state,
...savedState
})
}
} catch (error) {
console.warn('Failed to restore persisted state:', error)
}
// Save state on mutations
store.subscribe((mutation, state) => {
try {
const stateToSave = paths.length > 0
? paths.reduce((obj, path) => {
obj[path] = state[path]
return obj
}, {})
: reducer(state)
storage.setItem(key, JSON.stringify(stateToSave))
} catch (error) {
console.warn('Failed to persist state:', error)
}
})
}
}
// store/index.js
import { createStore } from 'vuex'
import createPersistedState from './plugins/persistence'
const store = createStore({
state: {
user: null,
preferences: {
theme: 'light',
language: 'en'
},
cart: []
},
mutations: {
SET_USER(state, user) {
state.user = user
},
SET_THEME(state, theme) {
state.preferences.theme = theme
},
ADD_TO_CART(state, item) {
state.cart.push(item)
}
},
plugins: [
createPersistedState({
key: 'my-app-state',
paths: ['user', 'preferences'], // Only persist specific state
storage: localStorage
})
]
})
This persistence plugin automatically saves specified state paths to localStorage after each mutation and restores them when the application initializes. The plugin supports selective persistence, custom storage backends, and error handling for robust state management across browser sessions.
Best Practice Note:
This state persistence pattern is used in CoreUI’s Vue applications for maintaining user preferences and session data. Always exclude sensitive information from persistence and consider using sessionStorage for temporary data that shouldn’t survive browser sessions.



