Skip to main content
Jack Sleight .DEV
Alpine

Force Alpine component re-initialisation on hot reload

In a previous post I outlined a method for hot reloading Statamic's live preview using Alpine's Morph plugin. It works, but there's an issue: Alpine components on the page don't re-initialise when the DOM is morphed. Depending on the component, this can break things when the new markup is applied.

The fix is to set a key attribute on every Alpine component before morphing. Alpine will re-initialise any component whose key changes, and even going from a blank key to no key is enough for it to count as different:

const text = await fetch(event.data.url).then((res) => res.text());
const updated = new DOMParser().parseFromString(text, 'text/html');
document.body.querySelectorAll('[x-data]').forEach((el) => el.setAttribute('key', ''));
Alpine.morph(document.body, updated.body);
const text = await fetch(event.data.url).then((res) => res.text());
const updated = new DOMParser().parseFromString(text, 'text/html');
document.body.querySelectorAll('[x-data]').forEach((el) => el.setAttribute('key', ''));
Alpine.morph(document.body, updated.body);

Bear in mind that this must be key, not :key as you'd use with x-for. Also, if you're already using key on your components for some other reason you may need to adjust the logic to avoid conflicts.

6th March 2026