Persist Plugin ($persist)
Automatically save state to localStorage (or any storage).
Persist Plugin
The official @alpinejs/persist plugin provides the $persist magic. It automatically saves a property's value to localStorage and restores it on page load. This is perfect for preserving UI state like dark mode, sidebar open/closed, or form drafts.
Installation & Registration
Code
npm install @alpinejs/persist
import persist from '@alpinejs/persist'
Alpine.plugin(persist)Basic Usage
Code
<div x-data="{ count: $persist(0) }">
<button @click="count++">Count: <span x-text="count"></span></button>
</div>Custom Storage Key
By default, the key is derived from the element hierarchy. You can specify a custom key for easier debugging.
Code
<div x-data="{ count: $persist(0).as('my-counter') }">...</div>Using Session Storage
You can switch to sessionStorage (or any other storage implementation) with the .using() method.
Code
$persist(0).using(sessionStorage)💡 Tip
Be careful with large objects – localStorage has a ~5MB limit. Persist only the necessary state.
Does $persist work with arrays and objects?
Yes, it serializes to JSON automatically. Just make sure the stored data doesn't contain functions or circular references.
Helpful? Share this page!↑ Back to top