Persisting State

localStorage With a Plugin

Persisting State

pinia-plugin-persistedstate hydrates stores from localStorage on app start and syncs them back on every change.

4 min read Level 2/5 #vue#pinia#persistence
What you'll learn
  • Install pinia-plugin-persistedstate
  • Mark a store with persist
  • Persist only specific keys

Persisting auth tokens, cart contents, or UI preferences across reloads is a one-line config when you use pinia-plugin-persistedstate.

Install

npm i pinia-plugin-persistedstate

Register the Plugin

// src/main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
import App from './App.vue'

const pinia = createPinia()
pinia.use(piniaPluginPersistedstate)

createApp(App).use(pinia).mount('#app')

Persist a Store

In a setup store, pass { persist: true } as the third argument to defineStore.

export const useAuthStore = defineStore(
  'auth',
  () => {
    const token = ref<string | null>(null)
    const userId = ref<string | null>(null)
    return { token, userId }
  },
  { persist: true },
)

On load, the store is hydrated from localStorage. On every change, it’s written back.

Cherry-Pick Keys

Persist only token, not the whole store:

{ persist: { pick: ['token'] } }

Choose a Storage

Use sessionStorage or a custom backend:

{ persist: { storage: sessionStorage } }

Avoid persisting sensitive data in localStorage — anything readable from JS is readable to XSS.

HTTP — fetch & axios →