Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 38 ยท Plugins and Persistence

Persisting Pinia State Across Reloads

Save Pinia state so it survives a page reload: write a small persistence plugin with $subscribe, restore on creation, choose what to save and handle storage errors.

Pinia state lives in memory. Reload the page and it is gone: the cart empties, the theme resets, the half-written draft disappears. For many apps that is wrong. In this lesson you build a persistence plugin from scratch to understand exactly what the popular libraries do, so you can use them (or replace them) with confidence.

The recipe has three steps: restore saved state when the store is created, save whenever the state changes, and limit what gets saved.

The live examples run in a sandbox that blocks localStorage, so they use a small in-memory stand-in with the same getItem/setItem methods. Your own app would pass window.localStorage instead. The Reload button in the examples recreates the whole pinia, which is what a page reload does to in-memory state.

Restore, then save

A persistence plugin does this for each store:

JavaScript
pinia.use(({ store }) => {
  const key = `pinia:${store.$id}`;

  const saved = storage.getItem(key);
  if (saved) {
    store.$patch(JSON.parse(saved));      // restore
  }

  store.$subscribe((mutation, state) => {
    storage.setItem(key, JSON.stringify(state));   // save
  });
});

$patch merges saved values into the fresh initial state. $subscribe runs after every change, so the saved copy always matches memory. Because the plugin is registered once, every store is persisted with no extra code in the store.

Run it. Press Reload to simulate a page refresh and watch the counter come back.

A persistence plugin in about ten lines

(The "Saved JSON" line is not reactive on purpose: it refreshes when the component re-renders.)

Choosing what to save

Saving everything is rarely right. A form might hold an isSubmitting flag that must not survive a reload, and tokens may belong in another place. Let stores say what to save with a custom option, the technique from the previous lesson:

JavaScript
defineStore("settings", {
  state: () => ({ theme: "light", search: "", isOpen: false }),
  persist: { pick: ["theme"] },
});

function persistPlugin({ store, options }) {
  if (!options.persist) return;      // opt-in per store
  const pick = options.persist.pick;
  // ...
  store.$subscribe((_, state) => {
    const out = pick ? Object.fromEntries(pick.map((k) => [k, state[k]])) : state;
    storage.setItem(key, JSON.stringify(out));
  });
}

Opt-in is safer than opt-out: a new store is not saved by accident. Here is a full version with pick, a custom key and a safe restore:

Opt-in persistence with pick

Change the theme and the search text, press Reload: the theme returns, the search box is empty again, and the notes store never wrote anything.

Things that go wrong

  • Storage is unavailable. Private modes, blocked cookies and quota limits make setItem throw. Always use try/catch and let the app keep working.
  • The saved shape is old. After you rename or remove a state key, old saved data may not fit. Keep a version field in what you save and discard saved data when it does not match.
  • Non-JSON values. Date, Map, Set and functions do not survive JSON.stringify. Convert them or choose another serializer.
  • Secrets. Never put access tokens or personal data in localStorage casually: any script on the page can read it.
  • Saving too often. $subscribe fires on every keystroke bound to state. Debounce for large stores.
  • SSR. There is no localStorage on the server. Restore only in the browser; see SSR and hydration.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which pair of store features does a basic persistence plugin use?

    Saved data is merged back with $patch when the store is created, and $subscribe saves after every state change.
  2. 2. Why is an opt-in persist option safer than saving every store?

    With opt-in, only stores that ask for persistence are saved, so temporary or sensitive stores stay out of storage.
  3. 3. What should a persistence plugin do when localStorage.setItem throws?

    Storage can be full or blocked; catching the error keeps the app usable even if saving fails.
  4. 4. Which value does JSON.stringify NOT preserve properly?

    A Map serializes as an empty object. Convert it to an array or object before saving.

Summary

  • Persistence = restore with $patch when the store is created + save with $subscribe.
  • A plugin does it for every store; a custom option lets each store opt in and choose what to save.
  • Guard storage calls with try/catch, version the saved data and avoid secrets.
  • Do not restore on the server; only the browser has localStorage.

Next: The persistedstate Plugin and Storage Options