ilokesto

Persist migrations

persist serializes { state, version } to browser storage. The version is the length of the migration array.

Storage types

  • { local: key } uses localStorage.
  • { session: key } uses sessionStorage.
  • { cookie: key } uses document.cookie.

Migrations

Migration functions run from the stored version index until the latest migration. The result is written back with the new version.

persist({ theme: 'light', count: 0 }, {
  local: 'settings',
  migrate: [
    (old) => ({ theme: String(old), count: 0 }),
    (old) => ({ ...old, count: Number(old.count ?? 0) }),
  ],
});

Caveats

  • Migrations are only attempted for local and cookie storage.
  • session storage does not accept migrate in the public type.
  • Values are JSON parsed and stringified; non-JSON state should be adapted before persistence.
  • Browser storage failures are caught and logged only when window exists.

On this page