Description: Easily persist component data or store data to your browser's localStorage using Alpine's $persist magic property. This improves User Experience (UX) by remembering user choices or component states across browser sessions (e.g., closing and reopening the browser) or page reloads.
Alpine.$persist(defaultValue): This is the core magic function from Alpine's Persist plugin (which is included by default in the AlpineJS CDN build). You use it to initialize a data property within your Alpine component, signaling that its value should be persisted.
localStorage.localStorage (e.g., on first visit), it uses the defaultValue you provide.localStorage.Example usage within an Alpine.data component definition:
// In Alpine.data()
// 'darkModeEnabled' will be false by default if not found in localStorage
darkModeEnabled: Alpine.$persist(false)
.as('storageKey'): This is a method chained onto Alpine.$persist(). It allows you to specify a custom name (the "key") for how the data is stored in localStorage.
.as(), Alpine generates a key, often based on the component's internal ID and the property name. This generated key can be less predictable and harder to debug..as('yourCustomKey') gives you explicit control over the localStorage key, making it easier to identify in developer tools and less prone to accidental changes if component structure is refactored.Example usage:
// In Alpine.data()
// Persists 'app_theme' with 'light' as default, stored under 'myAppThemeKey'
appTheme: Alpine.$persist('light').as('myAppThemeKey')
localStorage: This is a standard Web Storage API provided by modern browsers. It allows web applications to store data locally within the user's browser as key-value pairs.
localStorage persists even after the browser window is closed and reopened.example.com is separate from anothersite.com.Alpine.$persist() uses localStorage "under the hood" to save and retrieve your component's state. You can inspect localStorage content using your browser's developer tools (usually found in the "Application" or "Storage" tab).localStorage are strings; $persist handles JSON serialization/deserialization:
Native localStorage can only store string values. If you attempt to store an object or array directly using localStorage.setItem(), it will be converted to a generic string like "[object Object]".
Alpine's $persist magic intelligently handles this for you by automatically using JSON.stringify() when saving complex data types (objects, arrays) and JSON.parse() when retrieving them. This is very convenient but important to be aware of, especially if you're debugging or mixing $persist with manual localStorage operations. The defaultValue you provide to $persist(defaultValue) also helps Alpine understand the expected data type.
.as('storageKey') are unique to avoid clashes:
The key you provide to .as('someKey') is global within the browser's localStorage for that specific domain. If multiple Alpine components, different parts of your application, or even different applications hosted on the same domain use the exact same localStorage key, they will overwrite each other's data. This can lead to unpredictable behavior and bugs that are hard to trace.
Always choose unique and descriptive keys. A common practice is to prefix keys with your application's name or a unique identifier (e.g., .as('myAppName_userPreferences')).
$persist saves changes to localStorage immediately, the "persistence across sessions" aspect is best demonstrated when the user reloads the page or closes and reopens the browser tab/window. The component should then initialize with the previously saved state, proving that the data was indeed persisted. Our working example below will explicitly guide you to refresh the page to observe this.
Current selected theme:
Test Persistence:
Select a theme using the buttons above. The page's appearance will change.
Then, refresh this page (you can use Ctrl+R on Windows/Linux or Cmd+R on macOS).
Your selected theme should be remembered and automatically reapplied! This demonstrates that the choice was persisted in localStorage.
You can also inspect localStorage in your browser's developer tools (Application > Local Storage) to see the key user_app_theme_preference and its value.