Skip to content

persist: setting a persisted value to undefined poisons localStorage, breaks component on next load #4877

Closed

Description

@Xuepoo

Description

When a $persist-ed value is set to undefined (e.g. delete this.foo or this.foo = undefined), the next page load throws a SyntaxError and the component fails to initialize.

Repro

<div x-data="{ foo: $persist('bar').as('my-foo') }">
    <button @click="foo = undefined">Clear</button>
    <span x-text="foo"></span>
</div>
  1. Load page, click "Clear" → foo becomes undefined
  2. Reload → SyntaxError: "undefined" is not valid JSON, component never initializes
  3. The my-foo key in localStorage is now permanently poisoned until manually cleared

Root cause

In storageSet (packages/persist/src/index.js), storage.setItem(key, JSON.stringify(value)) is called unconditionally. JSON.stringify(undefined) returns JS undefined (not a string), which the Web Storage API coerces into the literal string "undefined" before storing. On the next load, storageGet calls JSON.parse("undefined"), which throws.

The read side was guarded against undefined recently (dummy storage fix + missing-key fallback), but the write side was not.

Expected behavior

Setting a persisted value to undefined should either remove the persisted key or skip writing it, so the value falls back to its initial value on the next load — not crash.

Environment

  • Alpine version: v3.16.1
  • Browser: any (localStorage / sessionStorage / custom storages)

Proposed fix

PR #4876 skips the write and removes the key when the value is undefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions