How to persist Pinia state
Persisting Pinia state ensures your Vue 3 application maintains user data across browser sessions, improving user experience and reducing data loss.
As the creator of CoreUI with extensive Vue development experience since 2014, I’ve implemented state persistence in numerous dashboard applications for user preferences and application settings.
The most effective approach uses the pinia-plugin-persistedstate plugin for automatic state synchronization with localStorage.
This solution provides seamless persistence without manual store management while supporting selective state persistence.
Install and configure the pinia-plugin-persistedstate plugin for automatic Pinia state persistence.
// main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)
app.use(pinia)
// store/user.js
export const useUserStore = defineStore('user', {
state: () => ({
name: '',
preferences: {}
}),
actions: {
updateName(newName) {
this.name = newName
}
},
persist: true
})
This code installs the persistence plugin globally and enables it for specific stores using persist: true. The store automatically saves state changes to localStorage and restores them when the application loads. You can configure specific persistence options including storage type (localStorage/sessionStorage), key names, and which state properties to persist for fine-grained control.
Best Practice Note:
This is the persistence strategy we use in CoreUI Vue dashboard templates for maintaining user preferences.
Use selective persistence with persist: { paths: ['name'] } to persist only specific state properties and optimize storage usage.



