Skip to content

$persist initial value gets overwritten with undefined when localStorage is unavailable #4866

Closed

Description

@hamdyelbatal122

Summary

When localStorage is disabled or unavailable (for example, in Safari Private Browsing mode, restricted iframe contexts, or SSR), Alpine's $persist falls back to an in-memory Map storage.

In this fallback state, any property initialized with $persist(initialValue) loses its initial value and gets set to undefined.

Reproduction Steps

  1. Disable localStorage (or open Safari in Private Browsing mode where accessing localStorage throws a SecurityError).
  2. Initialize an Alpine component with a persisted property:
<div x-data="{ count: $persist(10) }">
    <span x-text="count"></span>
</div>
  1. Observe the rendered text.

Expected Behavior

count should hold its default value of 10.

Actual Behavior

count becomes undefined on component initialization.

Root Cause

According to the Web Storage specification, localStorage.getItem() returns null when a key does not exist. However, the in-memory fallback uses dummy.get.bind(dummy) (from a JS Map), which returns undefined for missing keys.

Because storageHas() checks storage.getItem(key) !== null, the condition undefined !== null evaluates to true. Alpine interprets this as "the item already exists in storage", calls storageGet(), receives undefined, and overwrites the initial value 10 with 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