Designing modular Pinia persistence plugin with versioned migrations
The plan defines a Pinia plugin that hydrates each modular store from localStorage keyed by store ID, stores a version with the persisted state, and runs defined migration functions sequentially if loaded state is outdated, then patches the store. It supports per-store config including version, storage key, and migration map, enabling safe state upgrades across versions by chaining migration functions before applying state.Implementing migration chain with explicit target versions
The persistence plugin now supports multi-step migrations by defining each migration as an object specifying the next target version and a migration function; it iterates through these steps until reaching the current version, applying each transformation sequentially before patching the store.
Below is one way to structure a reusable “persist + hydrate + migrate” plugin for Pinia and then use it in modular stores. The key points are:
- Each store declares if/how it should be persisted:
persist: { version, key?, migrations? }.
- On store creation, the plugin tries to read from
localStorage.
- If there is persisted data and its version differs from the current store version, the plugin runs the needed migration(s) before patching the store.
- All subsequent store changes are saved back with the current version.
Persist + Migrate Plugin (plugins/persistWithVersion.ts)
import type { PiniaPluginContext } from 'pinia'
// A migration step declares where it migrates *from* and *to*.
type MigrationStep = {
to: string
migrate: (state: any) => any
}
export type PersistWithVersionOptions = {
key?: string // storage key (default: store.$id)
version: string // current version of the store
storage?: Storage // default: window.localStorage
migrations?: Record<string, MigrationStep>
}
export function persistWithVersionPlugin({ store, options }: PiniaPluginContext) {
const persist = (options as any).persist as PersistWithVersionOptions | undefined
if (!persist) return
const storage = persist.storage ?? (typeof localStorage !== 'undefined' ? localStorage : undefined)
if (!storage) return
const key = persist.key ?? `__pinia__${store.$id}`
const targetVersion = persist.version
// --- Hydrate ---
const raw = storage.getItem(key)
if (raw) {
try {
const parsed = JSON.parse(raw)
let savedVersion: string = parsed.__version ?? parsed.version ?? '0.0.0'
let savedState: any = parsed.state ?? parsed
// --- Migrate if needed ---
if (savedVersion !== targetVersion) {
const migrations = persist.migrations ?? {}
let safety = 0
while (savedVersion !== targetVersion && safety < 20) { // avoid infinite loops
const step = migrations[savedVersion]
if (!step) {
console.warn(`[Pinia persist] No migration found for ${savedVersion} -> ${targetVersion} on store ${store.$id}.`)
break
}
savedState = step.migrate(savedState)
savedVersion = step.to
safety++
}
if (savedVersion !== targetVersion) {
console.warn(`[Pinia persist] Could not fully migrate store ${store.$id}.`)
}
}
store.$patch(savedState)
} catch (err) {
console.error(`[Pinia persist] Failed to hydrate ${store.$id}`, err)
}
}
// --- Persist on changes ---
store.$subscribe((_mutation, state) => {
const payload = JSON.stringify({
__version: targetVersion,
state
})
storage.setItem(key, payload)
})
}
Pinia Setup (main.ts)
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { persistWithVersionPlugin } from './plugins/persistWithVersion'
import App from './App.vue'
const pinia = createPinia()
pinia.use(persistWithVersionPlugin)
createApp(App).use(pinia).mount('#app')
Example Store With Migration (stores/useAuthStore.ts)
import { defineStore } from 'pinia'
type AuthState = {
token: string
user: { id: string; name: string } | null
// In v1.0 we used `jwt` instead of `token`, and `userName` instead of `user.name`
}
export const useAuthStore = defineStore('auth', {
state: (): AuthState => ({
token: '',
user: null
}),
actions: {
setToken(token: string) {
this.token = token
},
setUser(user: AuthState['user']) {
this.user = user
}
},
// Persist config for this store
persist: {
version: '1.1',
key: 'myapp-auth',
migrations: {
// from 1.0 -> 1.1
'1.0': {
to: '1.1',
migrate: (oldState: any): AuthState => {
// Example transformation: rename jwt->token, userName->user.name
const token = oldState.jwt ?? ''
const name = oldState.userName ?? ''
return {
token,
user: name ? { id: oldState.userId ?? '', name } : null
}
}
}
}
}
})
Notes
- You can define as many stores as you want; each can have its own
persist.version, storage key, and migrations.
- For multi-step migrations, chain migration steps: each step’s
to version becomes the next step’s from.
- If you have a global app version, you can map that to each store’s
persist.version or compute it once and pass it in.
- You may swap out
localStorage with another Storage implementation by supplying storage in persist.
With this setup, whenever the app loads, persisted state is read from localStorage, migrated if needed, and then patched into the store. Subsequent changes are automatically saved with the current version tag.