Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 38 ยท Plugins and Persistence

The persistedstate Plugin and Its Options

Use pinia-plugin-persistedstate in a real project: install it, set persist options like key, pick, omit, storage and serializer, and test the same ideas live.

You built a persistence plugin by hand in the last lesson. For production apps you do not have to maintain one: the community plugin pinia-plugin-persistedstate does the same job with more options, good defaults and TypeScript types. This lesson shows how to install it and what each option means. Because the real package needs npm, the live examples use a hand-written stand-in that accepts the same option names, so you can experiment with their effects in the browser.

Installing and registering

In a real project (read-only code, it needs a package manager):

Terminal
npm install pinia-plugin-persistedstate
JavaScript
// main.js
import { createPinia } from "pinia";
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";

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

Then a store opts in with a persist option. With an options store, the option sits next to state:

JavaScript
export const useSettingsStore = defineStore("settings", {
  state: () => ({ theme: "light", language: "en" }),
  persist: true,
});

With a setup store, the option is the third argument:

JavaScript
export const useSettingsStore = defineStore(
  "settings",
  () => {
    const theme = ref("light");
    return { theme };
  },
  { persist: true },
);

persist: true saves the whole state to localStorage under the store id, and restores it when the store is created.

The persist options

Pass an object instead of true to tune the behavior:

Option Meaning
key Storage key. Default is the store id.
storage Where to save: localStorage (default), sessionStorage or any object with getItem and setItem.
pick Array of state paths to save; everything else is ignored.
omit Array of state paths to exclude; everything else is saved.
serializer An object { serialize, deserialize }; default is JSON.stringify / JSON.parse.
beforeHydrate Callback before restored state is applied.
afterHydrate Callback after restored state is applied.
debug Log errors to the console.

Paths can be nested, such as "user.preferences.theme". Use pick or omit, whichever list is shorter.

JavaScript
persist: {
  key: "my-app:cart",
  storage: sessionStorage,       // gone when the tab closes
  omit: ["isCheckingOut"],       // never save transient flags
}

Several destinations at once

persist can be an array. Each entry is an independent configuration, so you can send the theme to localStorage and the draft to sessionStorage:

JavaScript
persist: [
  { key: "prefs", storage: localStorage, pick: ["theme"] },
  { key: "draft", storage: sessionStorage, pick: ["draft"] },
]

Global defaults

createPersistedState makes a plugin with defaults for every store, for example a key prefix or a different storage:

JavaScript
import { createPersistedState } from "pinia-plugin-persistedstate";

pinia.use(
  createPersistedState({
    storage: sessionStorage,
    key: (id) => `__myapp__${id}`,
    auto: true,       // persist every store without writing persist: true
  }),
);

With auto: true, stores are persisted by default and opt out with persist: false.

Trying the options live

This stand-in (about 30 lines) implements key, storage, pick, omit and serializer. It is not the real library, but the options behave the same way. Notice that the two "storages" are separate in-memory objects, so you can see which one received what.

A stand-in with the persistedstate options

Type a draft, change the theme, then press Reload page: both come back. Press Close tab: the theme returns, the draft is gone, just like the real sessionStorage.

A custom serializer

The default serializer is JSON, which cannot hold a Set. A serializer fixes that by converting on the way in and out:

A serializer for a Set

The saved text is a plain array, and after reload the store rebuilds a real Set.

Choosing sensible defaults

  • Save preferences (theme, language), drafts and non-sensitive UI state.
  • Do not save server data that should be fetched fresh, or anything secret.
  • Prefer pick for tiny sets of keys and omit for "everything except".
  • Use sessionStorage for state that should end with the tab.
  • Nuxt has its own module, @pinia-plugin-persistedstate/nuxt, which defaults to cookies so the server can read the saved state. See Pinia in Nuxt.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where does the persist option go in a setup store?

    Setup stores take options as the third argument: defineStore(id, setupFn, { persist: true }).
  2. 2. What does persist: true do?

    With true, the default configuration applies: all state, localStorage, key equal to the store id.
  3. 3. You want the theme in localStorage and a draft in sessionStorage. What do you use?

    persist accepts an array; each item has its own key, storage and pick or omit.
  4. 4. When do you need a custom serializer?

    JSON loses Sets and Maps; a serializer converts them to and from a JSON-safe form.

Summary

  • Install pinia-plugin-persistedstate, call pinia.use(...), then add persist: true to stores.
  • Options: key, storage, pick, omit, serializer, beforeHydrate, afterHydrate, debug.
  • persist can be an array to write different parts to different places.
  • createPersistedState({...}) sets global defaults, including auto: true.
  • Save preferences and drafts, not secrets or fresh server data.

Next: Testing Stores with Vitest