@aaronbushnell/alpinejs-history
v1.0.7
Published
Alpine.js plugin to persist state in the URL query string with browser history traversal (supports objects via bracket params).
Maintainers
Readme
alpinejs-history
Persist Alpine.js state in the URL query string with browser history support.
This plugin lets you bind Alpine state to the URL so:
- state is shareable via links
- Back/Forward buttons rehydrate UI state
- text input doesn’t spam browser history
- complex objects use conventional bracketed query params
Designed to feel like @alpinejs/persist.
Install
npm install @aaronbushnell/alpinejs-historySetup
import Alpine from "alpinejs"
import history from "@aaronbushnell/alpinejs-history"
Alpine.plugin(history)
Alpine.start()Basic usage
<div x-data="{ open: $history(false).as('open') }">
<button @click="open = !open">Toggle</button>
<div x-show="open" x-cloak>
hello
</div>
</div>URL output
?open=true
?open=false- Booleans and numbers use
pushState - Back/Forward buttons traverse state correctly
Text input (debounced)
<div x-data="{ query: $history(null).as('query') }">
<input x-model="query" placeholder="Search…" />
</div>URL output
?query=hello+world- Writes are debounced
- Uses
replaceStateto avoid history spam while typing - Back/Forward rehydrates state without page reload
Objects and forms
<div
x-data="{
form: $history({
name: '',
email: ''
}).as('form')
}"
>
<input x-model="form.name" placeholder="Name" />
<input x-model="form.email" placeholder="Email" />
</div>URL output
?form[name]=Aaron&form[email][email protected]- Uses conventional bracketed query params
- Nested objects and arrays are supported
- Rehydrates cleanly on reload or history navigation
Aliases
open: $history(false).as('menu')?menu=trueAliases work the same way as @alpinejs/persist.
History behavior
| Value type | History method | Notes |
| --- | --- | --- |
| Boolean / Number | pushState | Traversable with Back/Forward |
| String | replaceState | Debounced (typing-friendly) |
| Object / Array | replaceState | Debounced form editing |
Security notes
- URL values are untrusted input
- Avoid rendering
$history()values withx-htmlunless sanitized - This plugin blocks
__proto__,constructor, andprototypekeys to reduce prototype pollution risks
Compatibility
- Alpine.js v3+
- ESM-only package (no bundler required)
- Works with Vite, Webpack, Rollup, etc.
License
MIT
