Skip to content

Fix fallback storage returning undefined for missing keys - #4867

Open
hamdyelbatal122 wants to merge 1 commit into
alpinejs:mainfrom
hamdyelbatal122:fix/persist-dummy-storage-null-check
Open

Fix fallback storage returning undefined for missing keys#4867
hamdyelbatal122 wants to merge 1 commit into
alpinejs:mainfrom
hamdyelbatal122:fix/persist-dummy-storage-null-check

Conversation

@hamdyelbatal122

Copy link
Copy Markdown

Fixes #4866

What was the issue?

When localStorage is unavailable or throws an exception, $persist falls back to an in-memory Map storage (dummy).

When checking if a persisted key exists, storageHas() ran storage.getItem(key) !== null. Because Map.prototype.get() returns undefined (unlike localStorage.getItem() which returns null), storageHas() returned true for keys that were never set. This caused Alpine to attempt reading the value, receiving undefined, and overwriting the initial value passed to $persist().

Changes made

  1. Updated the fallback dummy storage getItem handler to return null when a key is missing from the map, bringing it in line with the standard Storage.getItem() specification.
  2. Updated storageHas() to check that the returned value is neither null nor undefined.

Verification

  • Tested normal localStorage functionality — remains unchanged.
  • Tested fallback memory storage — initial values are now preserved correctly when localStorage throws or is absent.

@joshhanley joshhanley changed the title fix(persist): fix fallback storage returning undefined for missing keys Fix fallback storage returning undefined for missing keys Aug 1, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

1 participant