The Complete Alpine.js Guide

By

Updated

Tagged: Alpine.js

Learn Alpine.js 3 from scratch: x-data, x-on, x-show vs x-if, x-model, keyed x-for, async fetch, Alpine.data, Alpine.store, plugins, htmx pairing, and CSP.

This guide is an in-depth guide to Alpine.js, version 3.

If you build server-rendered web pages and want client-side interactivity without pulling in a massive JavaScript framework or setting up a complex bundler, Alpine.js is hard to beat.

I use Alpine on almost every server-rendered site I build. With a single <script> tag, Alpine lets us build dropdowns, modals, tabs, live filter boxes, character counters, toast notifications, and form helpers right inside our HTML.

In this guide, we start from zero and build up to production patterns.

We install Alpine, learn how its Proxy reactivity works, master every core directive (x-data, x-on, x-bind, x-show, x-if, x-for, x-model, x-transition, x-init, x-effect), fetch async data cleanly, extract growing components into reusable Alpine.data() modules, share global state with Alpine.store(), wire up official plugins, pair Alpine with htmx, and ship accessible, unit-tested, CSP-safe components.

Every version and bundle size measurement in this guide was verified live on my Mac:

SoftwareVersion / Measurement
Alpine.js3.17.6
Minified CDN bundle (dist/cdn.min.js)55,969 bytes (~15 KB gzipped)
Node.js22.23.5

Interactive Alpine.js Cheatsheet

Explore core directives with live mini-demos built with Alpine itself:

Alpine.js Directive CheatsheetInteractive · runs in your browser

No directives match that filter.

What is Alpine.js (and when to use it)?

Alpine.js is a small reactive JavaScript library you write directly inside HTML attributes.

I like to treat Alpine as the missing reactive layer for normal HTML pages. We do not need JSX, a virtual DOM, a client-side router, or a build step. Your server renders plain HTML (from Astro, Node.js, Laravel, Rails, Django, Go, or static files), and Alpine wakes up the small interactive pockets on the page.

Here is how Alpine’s reactive loop works:

User clicks @clickx-data='{ open:false }'(Reactive Proxy)open = !openAlpine updates onlybound DOM elementsDropdown opens orcloses

You declare a tiny piece of state on a container element with x-data, listen for events with @click, and show or hide elements with x-show. Alpine wraps your state object in a native JavaScript Proxy, so whenever a property changes, every element bound to that property updates automatically.

Alpine.js vs React vs Vanilla JavaScript

FactorVanilla JSAlpine.jsReact / Vue
Bundle size0 KB~15 KB gzipped~45 KB to 150+ KB
Build step needed?NoNo (optional)Almost always
DOM updatesManual querySelectorAutomatic via ProxyVirtual DOM / compiler
Markup lives inHTMLHTML attributesJSX / .vue components
Best suited forOne tiny scriptInteractive pockets on server-rendered pagesComplex client-heavy SPAs

My rule of thumb is straightforward.

  • Pick Alpine.js for dropdowns, tabs, modals, accordions, dark-mode toggles, client-side list filtering, copy-to-clipboard buttons, multi-step forms, and server-rendered apps (especially paired with htmx).
  • Pick React, Vue, or Svelte for rich offline-first editors, drawing canvases, or massive dashboards where the entire application lives inside the browser.

Installing Alpine.js and running your first component

You can start using Alpine in ten seconds with zero build tools, or bundle it with Vite if you already have a Node project.

Option 1: Drop in one <script> tag (zero build step)

Add Alpine’s CDN script inside your <head> with the defer attribute (or self-host cdn.min.js in your public/vendor/ folder for production):

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta
    name="viewport"
    content="width=device-width, initial-scale=1"
  />
  <title>Alpine Demo</title>
  <script
    defer
    src="https://unpkg.com/alpinejs@3.17.6/dist/cdn.min.js"
  ></script>
</head>
<body>
  <div x-data="{ count: 0 }">
    <button type="button" @click="count++">
      Clicked <span x-text="count"></span> times
    </button>
  </div>
</body>
</html>

Save that as index.html, open it in your browser, and click the button. The counter increments right away.

The defer attribute matters. It lets the browser parse your HTML first and then execute Alpine once the DOM is ready.

Your second component: a simple show/hide toggle

Right beside that counter inside <body>, drop in a tiny toggle component:

<div x-data="{ open: false }">
  <button type="button" @click="open = !open">
    <span x-text="open ? 'Hide details' : 'Show details'"></span>
  </button>

  <p x-show="open">
    Alpine updates this text with zero querySelector calls.
  </p>
</div>

Click the button twice and watch two things happen at once. The paragraph appears and hides, and the button text switches between “Show details” and “Hide details”.

That small loop is the core of Alpine. You declare local state in x-data, change it on an event like @click, and let HTML directives keep the page in sync.

Here is the verified alpinejs 3.17.6 bundle size check and node --test unit test run from my terminal (55,969 bytes minified):

Verifying Alpine.js 3.17.6 bundle size and counter unit test

Option 2: Install via npm with Vite or Astro

If your project already bundles JavaScript with Vite or Astro, install alpinejs from npm so your version stays pinned and loads locally:

npm install alpinejs

Then import and start Alpine in your entry script:

import Alpine from 'alpinejs'

window.Alpine = Alpine

// Register plugins, Alpine.data(), and Alpine.store() BEFORE Alpine.start()
Alpine.start()

Wait to call Alpine.start() until after you have registered all plugins, Alpine.data() components, and Alpine.store() stores. Calling Alpine.start() too early means your components boot before their factories exist.

Reactive state with x-data, x-text, and x-html

Every Alpine component begins with x-data.

Scoping state with x-data

Putting x-data on an element turns that element and everything nested inside it into a reactive component. Two sibling elements with their own x-data stay completely isolated from each other:

<div x-data="{ open: false }">
  <button @click="open = !open">Menu 1</button>
  <p x-show="open">Content for menu 1</p>
</div>

<div x-data="{ open: false }">
  <button @click="open = !open">Menu 2</button>
  <p x-show="open">Content for menu 2</p>
</div>

Clicking Menu 1 only toggles the first open variable.

You can also put helper methods and JavaScript getters directly inside x-data:

<div
  x-data="{
    price: 29,
    quantity: 1,
    get total() {
      return this.price * this.quantity
    },
    increment() {
      this.quantity++
    },
    decrement() {
      if (this.quantity > 1) this.quantity--
    }
  }"
>
  <button @click="decrement()">-</button>
  <span x-text="quantity"></span>
  <button @click="increment()">+</button>
  <p>Total: $<span x-text="total"></span></p>
</div>

If an element does not need local state yet (for example, it only uses @click or reads from a global $store), write bare x-data with no value.

Nested x-data scope inheritance

Child x-data components automatically inherit properties from parent x-data scopes, just like JavaScript closures:

<div x-data="{ currency: 'EUR' }">
  <div x-data="{ price: 49 }">
    <p><span x-text="price"></span> <span x-text="currency"></span></p>
  </div>
</div>

Rendering text safely with x-text vs x-html

x-text sets an element’s textContent. Any < or > characters are escaped automatically, so it is always safe against Cross-Site Scripting (XSS):

<div x-data="{ user: 'Flavio' }">
  <p>Welcome back, <strong x-text="user"></strong>!</p>
</div>

x-html sets innerHTML, which parses and renders raw HTML tags. Never pass untrusted user input or URL parameters to x-html, because an attacker can inject <img src=x onerror=...> and run arbitrary JavaScript in your visitor’s browser. Stick to x-text unless you are rendering trusted HTML generated by your own server.

Ignoring a subtree with x-ignore

If a block inside an Alpine component contains user-authored HTML or markup managed by another JavaScript library, add x-ignore on that wrapper so Alpine leaves it completely untouched:

<div x-ignore>
  <!-- Alpine skips everything inside here -->
</div>

Handling events with x-on (@)

Alpine listens for browser events using x-on:event, or its shorter @event alias that almost everyone writes in practice.

<div x-data="{ message: '' }">
  <button @click="message = 'Saved!'">Save</button>
  <p x-text="message"></p>
</div>

You can inspect the native DOM event object inside any handler using the $event magic property:

<input @input="console.log($event.target.value)" placeholder="Type here" />

Event modifiers that save boilerplate

Chain dot modifiers onto @event to handle common browser patterns without writing repetitive JavaScript:

ModifierWhat it doesExample
.preventCalls event.preventDefault()@submit.prevent="save()"
.stopCalls event.stopPropagation()@click.stop="select()"
.outsideFires when the user clicks outside the element@click.outside="open = false"
.windowAttaches the listener to window@keydown.escape.window="open = false"
.documentAttaches the listener to document@visibilitychange.document="pause()"
.onceRuns the handler only once@click.once="trackSignup()"
.debounce.300msWaits 300 ms after the last event before firing@input.debounce.300ms="search()"
.throttle.250msFires at most once every 250 ms@scroll.window.throttle.250ms="onScroll()"
.selfFires only when clicking the element itself, not children@click.self="closeModal()"
.passiveMarks scroll/touch listeners passive for smoother scrolling@touchstart.passive="onTouch()"

Keyboard shortcuts in one attribute

Alpine lets you filter keydown and keyup events by key names and modifier keys (cmd, ctrl, shift, alt, enter, escape, slash, arrow-down, arrow-up):

<div
  x-data="{ open: false }"
  @keydown.cmd.k.window.prevent="open = true"
  @keydown.ctrl.k.window.prevent="open = true"
  @keydown.escape.window="open = false"
>
  <button @click="open = true">Search (Cmd+K)</button>
  <div x-show="open" x-cloak>Command palette open!</div>
</div>

Look how clean a dropdown becomes when we combine .outside and .escape.window:

<div
  x-data="{ open: false }"
  @click.outside="open = false"
  @keydown.escape.window="open = false"
>
  <button type="button" @click="open = !open" :aria-expanded="open">
    Account
  </button>
  <ul x-show="open" x-transition x-cloak>
    <li><a href="/profile">Profile</a></li>
    <li><a href="/billing">Billing</a></li>
  </ul>
</div>

Clicking outside the dropdown or pressing Escape closes it cleanly with zero custom JavaScript.

Mastering x-bind, dynamic classes, styles, and x-show vs x-if

Most day-to-day UI work comes down to three jobs: binding HTML attributes, toggling CSS classes or styles, and showing or hiding parts of the page.

Let’s walk through each one with small HTML examples you can copy into a blank page and test right away.

Binding HTML attributes with x-bind (:)

Use x-bind:attr or the shorthand :attr to connect any HTML attribute to your component state.

Boolean attributes like disabled, readonly, required, and hidden get special treatment. When the bound expression is true, Alpine adds the attribute to the tag. When it becomes false, Alpine removes the attribute completely.

Here is a practical submit button that stays disabled until the user types an email, and locks itself while saving so nobody can click twice:

<form
  x-data="{
    email: '',
    saving: false,
    submit() {
      if (!this.email.trim() || this.saving) return
      this.saving = true
      setTimeout(() => {
        this.saving = false
        this.email = ''
      }, 1200)
    }
  }"
  @submit.prevent="submit()"
>
  <input
    type="email"
    x-model.trim="email"
    placeholder="you@example.com"
    :readonly="saving"
  />

  <button
    type="submit"
    :disabled="saving || !email.includes('@')"
    :aria-busy="saving"
  >
    <span x-text="saving ? 'Saving...' : 'Join list'"></span>
  </button>
</form>

Try typing an invalid string first. The button stays disabled until you type an @ sign, and clicking it switches the label to “Saving…” while :readonly stops edits mid-request.

You can bind any attribute this way, including :href, :src, :alt, :title, :aria-expanded, and :data-state.

Dynamic classes with :class

Passing a JavaScript object to :class lets you toggle one or more CSS classes based on boolean expressions.

Alpine merges your dynamic classes with any static class="..." already on the tag, so your base classes never get wiped out.

Let’s build a dark-mode card toggle using plain CSS and :class:

<style>
  .card {
    padding: 1.25rem;
    border-radius: 0.75rem;
    border: 1px solid #cbd5e1;
    background: #ffffff;
    color: #0f172a;
    max-width: 24rem;
  }
  .card.is-dark {
    background: #0f172a;
    color: #f8fafc;
    border-color: #334155;
  }
</style>

<section
  x-data="{ dark: false }"
  class="card"
  :class="{ 'is-dark': dark }"
>
  <p>
    Current theme:
    <strong x-text="dark ? 'Dark' : 'Light'"></strong>
  </p>

  <button
    type="button"
    @click="dark = !dark"
    :aria-pressed="dark"
  >
    Toggle theme
  </button>
</section>

If you want to toggle dark mode for the entire page instead of one card, add x-effect="document.documentElement.classList.toggle('dark', dark)" on the root wrapper.

When a class name contains a hyphen like is-dark, wrap it in single quotes inside the :class object. You can also put multiple space-separated classes in a single key, which is handy with utility frameworks like Tailwind CSS:

<button
  type="button"
  class="btn"
  :class="{
    'bg-blue-600 text-white': active,
    'bg-slate-100 text-slate-800': !active
  }"
>
  Settings
</button>

Here is a complete active navigation bar using :class and :aria-current:

<style>
  .nav { display: flex; gap: 0.5rem; margin-bottom: 1rem; }
  .nav-btn {
    padding: 0.45rem 0.9rem;
    border: 1px solid #cbd5e1;
    background: #f8fafc;
    border-radius: 0.4rem;
    cursor: pointer;
  }
  .nav-btn.is-active {
    background: #2563eb;
    color: #ffffff;
    border-color: #2563eb;
  }
</style>

<div x-data="{ tab: 'profile' }">
  <nav class="nav" aria-label="Account sections">
    <button
      type="button"
      class="nav-btn"
      :class="{ 'is-active': tab === 'profile' }"
      :aria-current="tab === 'profile' ? 'page' : null"
      @click="tab = 'profile'"
    >
      Profile
    </button>
    <button
      type="button"
      class="nav-btn"
      :class="{ 'is-active': tab === 'billing' }"
      :aria-current="tab === 'billing' ? 'page' : null"
      @click="tab = 'billing'"
    >
      Billing
    </button>
    <button
      type="button"
      class="nav-btn"
      :class="{ 'is-active': tab === 'security' }"
      :aria-current="tab === 'security' ? 'page' : null"
      @click="tab = 'security'"
    >
      Security
    </button>
  </nav>

  <p x-show="tab === 'profile'">Edit your name and photo.</p>
  <p x-show="tab === 'billing'" x-cloak>Download invoices.</p>
  <p x-show="tab === 'security'" x-cloak>Manage 2FA keys.</p>
</div>

Returning null or false for :aria-current tells Alpine to remove the attribute from inactive tabs.

Dynamic inline styles with :style

When a value changes continuously, like a percentage width or a user-picked color, bind inline CSS with :style.

Pass an object where keys are CSS property names (in kebab-case inside quotes or camelCase) and values are strings:

<div x-data="{ progress: 35, accent: '#2563eb' }">
  <div
    style="background: #e2e8f0; height: 12px; border-radius: 6px;"
  >
    <div
      style="height: 100%; border-radius: 6px; transition: width 0.2s;"
      :style="{
        width: progress + '%',
        backgroundColor: accent
      }"
    ></div>
  </div>

  <p>Completed: <strong x-text="progress + '%'"></strong></p>

  <button
    type="button"
    @click="progress = Math.min(100, progress + 15)"
    :disabled="progress >= 100"
  >
    Add 15%
  </button>
  <button type="button" @click="progress = 0">Reset</button>
</div>

Static style="..." rules stay intact while Alpine updates only the properties listed inside :style.

x-show vs x-if

Alpine gives us two ways to hide elements, and picking the right one prevents subtle bugs in real forms and layouts:

Featurex-showx-if
How it hidesSets style="display: none"Removes the node from the DOM
Tag requiredAny HTML elementMust sit on <template> with one root child
Works with x-transitionYesNo
Keeps child input state?Yes, text stays typedNo, resets when re-added
Included in <form> submit?Yes, still in the DOMNo, omitted when hidden

Look closely at the last two rows in that table.

With x-show="false", the element stays inside the DOM tree. If a user types inside an input, hides the section, and opens it again, their typed text is still there. And if that input sits inside a <form>, the browser still submits it and still runs HTML required checks on it.

With <template x-if="...">, Alpine deletes the element from the DOM when the condition turns false and recreates it fresh when the condition turns true.

Paste this quick demo into an HTML page to feel the difference yourself:

<div x-data="{ showBox: true }">
  <button type="button" @click="showBox = !showBox">
    Toggle both inputs
  </button>

  <div x-show="showBox">
    <label>
      Inside x-show (keeps text):
      <input type="text" placeholder="Type here, then toggle" />
    </label>
  </div>

  <template x-if="showBox">
    <div>
      <label>
        Inside x-if (resets text):
        <input type="text" placeholder="Type here, then toggle" />
      </label>
    </div>
  </template>
</div>

Type something into both inputs, click the button twice, and see what happens. The x-show input remembers what you wrote, while the x-if input comes back empty.

Use x-if whenever hidden form fields should skip validation and stay out of the submitted payload:

<div x-data="{ needsInvoice: false }">
  <label>
    <input type="checkbox" x-model="needsInvoice" />
    Need a VAT invoice
  </label>

  <template x-if="needsInvoice">
    <div>
      <label for="vat">VAT Number</label>
      <input id="vat" name="vat" type="text" required />
    </div>
  </template>
</div>

Always give <template x-if> one single root element inside it (like that <div>). Putting two sibling elements directly inside <template x-if> will fail.

Preventing flash of hidden content with x-cloak

Before Alpine boots on a slow mobile connection, an element with x-show="false" can briefly flash on screen.

Add one CSS rule to your global stylesheet and put x-cloak on every element that starts hidden:

[x-cloak] {
  display: none !important;
}
<div x-data="{ open: false }">
  <button type="button" @click="open = !open">Toggle</button>
  <div x-show="open" x-cloak>
    Hidden from the very first millisecond
  </div>
</div>

Alpine strips the x-cloak attribute the instant it initializes the component.

Smooth transitions with x-transition

Add bare x-transition beside x-show for a smooth fade and scale with zero custom CSS:

<div x-show="open" x-transition x-cloak>
  Smooth fade and scale with zero custom CSS
</div>

Customize it with built-in modifiers (x-transition.duration.200ms, x-transition.opacity, x-transition.scale.origin.top) or wire Tailwind CSS utility classes for full control:

<div
  x-show="open"
  x-cloak
  x-transition:enter="transition ease-out duration-200"
  x-transition:enter-start="opacity-0 -translate-y-1"
  x-transition:enter-end="opacity-100 translate-y-0"
  x-transition:leave="transition ease-in duration-150"
  x-transition:leave-start="opacity-100 translate-y-0"
  x-transition:leave-end="opacity-0 -translate-y-1"
>
  Dropdown panel
</div>

Mastering x-for for dynamic lists and tables

To render a list from an array in Alpine, place x-for on a <template> tag containing one single root element.

<div x-data="{ langs: ['HTML', 'CSS', 'JavaScript'] }">
  <ul>
    <template x-for="lang in langs" :key="lang">
      <li x-text="lang"></li>
    </template>
  </ul>
</div>

Alpine repeats the element inside <template> once per array item and updates the DOM whenever the array changes.

Why :key matters on editable or filtered lists

Whenever items can be deleted, sorted, inserted at the top, or filtered, add :key="item.id" pointing at a stable unique ID from your data.

Without a stable :key, Alpine reuses DOM nodes by their position in the array. If row 1 has a checked checkbox or focused text box and you delete row 1, that DOM state stays stuck on the new row 1 instead of disappearing with the deleted item.

Never use the array index as :key for mutable lists, because every index shifts when you remove an item from the middle.

Here is a tiny checklist where deleting an item keeps every remaining item’s state intact because each task carries a stable id:

<div
  x-data="{
    items: [
      { id: 10, label: 'Pack charger', checked: false },
      { id: 11, label: 'Print boarding pass', checked: true },
      { id: 12, label: 'Check passport', checked: false }
    ],
    remove(id) {
      this.items = this.items.filter((i) => i.id !== id)
    }
  }"
>
  <ul>
    <template x-for="item in items" :key="item.id">
      <li>
        <label>
          <input type="checkbox" x-model="item.checked" />
          <span x-text="item.label"></span>
        </label>
        <button type="button" @click="remove(item.id)">x</button>
      </li>
    </template>
  </ul>
</div>

Accessing the loop index

You can grab the zero-based position of each item using (item, index) in items.

That is useful for numbering rows (index + 1), styling alternating rows, or hiding a divider on the last item:

<div x-data="{ steps: ['Install', 'Configure', 'Deploy'] }">
  <ol>
    <template x-for="(step, index) in steps" :key="step">
      <li
        :style="{
          background: index % 2 === 0 ? '#f8fafc' : '#ffffff'
        }"
      >
        <strong x-text="index + 1"></strong>.
        <span x-text="step"></span>
        <span x-show="index === steps.length - 1">(Final)</span>
      </li>
    </template>
  </ol>
</div>

Looping over numbers and objects

You do not always need an array of objects.

Pass a number to x-for to repeat an element N times (1-based, from 1 up to N), which works well for star ratings or pagination buttons:

<div x-data="{ page: 1, totalPages: 4 }">
  <template x-for="n in totalPages" :key="n">
    <button
      type="button"
      @click="page = n"
      :disabled="page === n"
      x-text="n"
    ></button>
  </template>
  <p>Page <span x-text="page"></span></p>
</div>

To loop over a plain JavaScript object, convert it with Object.entries() right inside x-for:

<div
  x-data="{
    specs: { CPU: 'M4', RAM: '32 GB', Disk: '1 TB' }
  }"
>
  <dl>
    <template x-for="[key, val] in Object.entries(specs)" :key="key">
      <div>
        <dt x-text="key"></dt>
        <dd x-text="val"></dd>
      </div>
    </template>
  </dl>
</div>

Notice we wrapped <dt> and <dd> inside a single <div> so <template x-for> still has one root child.

Nested x-for loops

You can nest one <template x-for> inside another whenever your data is grouped into sections or categories.

The inner loop can read its own item variable, the outer loop’s variable, and any property on the parent x-data:

<div
  x-data="{
    selected: '',
    groups: [
      {
        id: 'front',
        name: 'Frontend',
        tools: [
          { id: 'f1', title: 'Alpine.js' },
          { id: 'f2', title: 'htmx' }
        ]
      },
      {
        id: 'back',
        name: 'Backend',
        tools: [
          { id: 'b1', title: 'Node.js' },
          { id: 'b2', title: 'SQLite' }
        ]
      }
    ]
  }"
>
  <p x-show="selected">
    Picked: <strong x-text="selected"></strong>
  </p>

  <template x-for="group in groups" :key="group.id">
    <section>
      <h3 x-text="group.name"></h3>
      <ul>
        <template x-for="tool in group.tools" :key="tool.id">
          <li>
            <button
              type="button"
              @click="selected = group.name + ': ' + tool.title"
              x-text="tool.title"
            ></button>
          </li>
        </template>
      </ul>
    </section>
  </template>
</div>

Filtering and sorting without mutating the original array

One of the easiest traps in JavaScript is calling .sort() directly on a reactive array inside a getter, like return this.books.sort(...).

Array .sort() mutates the array in place. Calling it on this.books permanently changes your original list order and can trigger extra reactive re-renders.

Always filter into a fresh array or clone first with spread syntax [...this.books] (or modern this.books.toSorted(...)) before sorting:

<div
  x-data="{
    query: '',
    category: 'all',
    sortBy: 'title',
    books: [
      { id: 1, title: 'JavaScript Handbook', cat: 'lang', pages: 39 },
      { id: 2, title: 'TypeScript Handbook', cat: 'lang', pages: 43 },
      { id: 3, title: 'Alpine.js Handbook', cat: 'ui', pages: 60 },
      { id: 4, title: 'CSS Handbook', cat: 'ui', pages: 52 }
    ],
    get filtered() {
      const q = this.query.trim().toLowerCase()
      const matches = this.books.filter((b) => {
        const catOk = this.category === 'all' || b.cat === this.category
        const textOk = !q || b.title.toLowerCase().includes(q)
        return catOk && textOk
      })
      return [...matches].sort((a, b) => {
        if (this.sortBy === 'pages-desc') return b.pages - a.pages
        if (this.sortBy === 'pages-asc') return a.pages - b.pages
        return a.title.localeCompare(b.title)
      })
    }
  }"
>
  <input
    type="search"
    x-model="query"
    placeholder="Search books..."
  />

  <select x-model="category">
    <option value="all">All topics</option>
    <option value="lang">Languages</option>
    <option value="ui">UI and CSS</option>
  </select>

  <select x-model="sortBy">
    <option value="title">Title (A-Z)</option>
    <option value="pages-desc">Pages (high to low)</option>
    <option value="pages-asc">Pages (low to high)</option>
  </select>

  <ul>
    <template x-for="book in filtered" :key="book.id">
      <li>
        <strong x-text="book.title"></strong>
        (<span x-text="book.pages"></span> pages)
      </li>
    </template>
  </ul>

  <p x-show="filtered.length === 0">No books match that filter.</p>
</div>

Because filtered never touches this.books, resetting query to '' and category to 'all' brings every original book back right away.

Mastering x-model with every HTML form control

x-model keeps form inputs and Alpine state in sync in both directions.

Typing in a field updates your reactive property, and changing that property in JavaScript updates the input on screen. Behind the scenes, Alpine wires up both the input’s :value (or :checked) and its @input (or @change) listener for you.

Let’s look at how x-model behaves with every standard HTML form control.

Text inputs and <textarea>

For <input type="text">, email, search, url, password, and <textarea>, x-model binds to a string property:

<div x-data="{ title: '', summary: '' }">
  <input
    type="text"
    x-model="title"
    placeholder="Article title"
  />

  <textarea
    x-model="summary"
    maxlength="160"
    rows="3"
    placeholder="Short summary..."
  ></textarea>

  <p>
    Title: <strong x-text="title || '(untitled)'"></strong>
  </p>
  <p>
    <span x-text="160 - summary.length"></span> characters left
  </p>
</div>

Single boolean checkbox vs array checkboxes

A single checkbox bound to a boolean property toggles between true and false:

<div x-data="{ newsletter: true }">
  <label>
    <input type="checkbox" x-model="newsletter" />
    Send weekly tips
  </label>
  <p x-text="newsletter ? 'Subscribed' : 'Not subscribed'"></p>
</div>

When you bind multiple checkboxes to an array property, Alpine checks each checkbox’s value attribute. Checking a box pushes its value into the array, and unchecking removes it:

<div x-data="{ topics: ['js'] }">
  <fieldset>
    <legend>Pick topics</legend>
    <label>
      <input type="checkbox" value="js" x-model="topics" />
      JavaScript
    </label>
    <label>
      <input type="checkbox" value="ts" x-model="topics" />
      TypeScript
    </label>
    <label>
      <input type="checkbox" value="css" x-model="topics" />
      CSS
    </label>
  </fieldset>

  <p>Selected: <span x-text="topics.join(', ') || 'none'"></span></p>
</div>

Radio buttons

Give every radio button in a group the same x-model and a unique value. Alpine sets the property to whichever radio is checked:

<div x-data="{ billing: 'yearly' }">
  <label>
    <input type="radio" value="monthly" x-model="billing" />
    Monthly ($12/mo)
  </label>
  <label>
    <input type="radio" value="yearly" x-model="billing" />
    Yearly ($99/yr)
  </label>

  <p>Chosen cycle: <strong x-text="billing"></strong></p>
</div>

Single and multiple <select> menus

A regular <select> binds to a single string, while <select multiple> binds to an array of selected option values:

<div x-data="{ plan: 'pro', regions: ['eu'] }">
  <label>
    Plan
    <select x-model="plan">
      <option value="free">Free</option>
      <option value="pro">Pro</option>
      <option value="team">Team</option>
    </select>
  </label>

  <label>
    Regions (hold Cmd/Ctrl for multiple)
    <select x-model="regions" multiple size="3">
      <option value="us">United States</option>
      <option value="eu">Europe</option>
      <option value="ap">Asia-Pacific</option>
    </select>
  </label>

  <p>
    Plan: <strong x-text="plan"></strong>,
    Regions: <strong x-text="regions.join(', ')"></strong>
  </p>
</div>

x-model modifiers in practice

You can chain dot modifiers onto x-model to shape values before they hit your state:

ModifierEffectBest used for
.numberCasts input text to a JavaScript numberQuantity, price, age
.trimStrips leading and trailing spacesEmails, handles, slugs
.debounce.300msWaits 300 ms after typing pausesLive search boxes
.lazyUpdates on change (blur) instead of every keyField validation
.booleanConverts "true" and "false" to booleansRadio/select flags
.fillReads server-rendered HTML value="..." on bootEdit forms from server

Why does .number matter so much? HTML inputs always return strings! Without .number, price + tax turns '10' + '2' into '102'. With .number, you get 12:

<div x-data="{ price: 20, qty: 2 }">
  <input type="number" x-model.number="price" min="0" />
  <input type="number" x-model.number="qty" min="1" />
  <p>Total: $<strong x-text="price * qty"></strong></p>
</div>

And .fill saves you on server-rendered edit pages. If your backend outputs <input name="email" value="flavio@example.com" x-model.fill="email" />, Alpine seeds email from the HTML value instead of overwriting it with ''.

Real-world example: live filter and validated contact form

Here is a practical two-part component combining .debounce.300ms, .trim, .lazy, .number, and every control type we just covered.

First, a debounced directory filter that waits 300 ms after you stop typing before filtering:

<div
  x-data="{
    search: '',
    role: 'all',
    availableOnly: false,
    people: [
      { id: 1, name: 'Elena Rossi', role: 'design', free: true },
      { id: 2, name: 'Marco Conti', role: 'dev', free: false },
      { id: 3, name: 'Sofia Neri', role: 'dev', free: true },
      { id: 4, name: 'Luca Bianchi', role: 'design', free: true }
    ],
    get matches() {
      const q = this.search.toLowerCase()
      return this.people.filter((p) => {
        if (this.role !== 'all' && p.role !== this.role) return false
        if (this.availableOnly && !p.free) return false
        return !q || p.name.toLowerCase().includes(q)
      })
    }
  }"
>
  <input
    type="search"
    x-model.debounce.300ms.trim="search"
    placeholder="Filter team..."
  />

  <select x-model="role">
    <option value="all">All roles</option>
    <option value="dev">Developers</option>
    <option value="design">Designers</option>
  </select>

  <label>
    <input type="checkbox" x-model="availableOnly" />
    Available only
  </label>

  <ul>
    <template x-for="person in matches" :key="person.id">
      <li>
        <strong x-text="person.name"></strong>
        (<span x-text="person.role"></span>)
      </li>
    </template>
  </ul>

  <p x-show="matches.length === 0">No teammates found.</p>
</div>

Second, a complete signup form using .lazy.trim on email, .number on seats, radio buttons, a checkbox agreement, and live validation feedback:

<form
  x-data="{
    name: '',
    email: '',
    seats: 1,
    tier: 'starter',
    agreed: false,
    submitted: false,
    errors: {},
    validate() {
      const errs = {}
      if (this.name.length < 2) {
        errs.name = 'Enter at least 2 characters.'
      }
      if (!this.email.includes('@') || !this.email.includes('.')) {
        errs.email = 'Enter a valid email address.'
      }
      if (this.seats < 1 || this.seats > 50) {
        errs.seats = 'Seats must be between 1 and 50.'
      }
      if (!this.agreed) {
        errs.agreed = 'Please accept the terms.'
      }
      this.errors = errs
      return Object.keys(errs).length === 0
    },
    submit() {
      this.submitted = this.validate()
    }
  }"
  @submit.prevent="submit()"
  novalidate
>
  <div>
    <label for="f-name">Name</label>
    <input id="f-name" type="text" x-model.trim="name" />
    <p x-show="errors.name" x-text="errors.name" role="alert"></p>
  </div>

  <div>
    <label for="f-email">Email (checks on blur)</label>
    <input
      id="f-email"
      type="email"
      x-model.lazy.trim="email"
      @change="validate()"
    />
    <p x-show="errors.email" x-text="errors.email" role="alert"></p>
  </div>

  <div>
    <label for="f-seats">Team seats</label>
    <input
      id="f-seats"
      type="number"
      x-model.number="seats"
      min="1"
      max="50"
    />
    <p x-show="errors.seats" x-text="errors.seats" role="alert"></p>
  </div>

  <fieldset>
    <legend>Tier</legend>
    <label>
      <input type="radio" value="starter" x-model="tier" />
      Starter ($10/seat)
    </label>
    <label>
      <input type="radio" value="pro" x-model="tier" />
      Pro ($20/seat)
    </label>
  </fieldset>

  <label>
    <input type="checkbox" x-model="agreed" />
    I agree to the terms of service
  </label>
  <p x-show="errors.agreed" x-text="errors.agreed" role="alert"></p>

  <p>
    Estimate:
    $<strong x-text="seats * (tier === 'pro' ? 20 : 10)"></strong>/mo
  </p>

  <button type="submit">Create workspace</button>

  <p x-show="submitted" x-cloak role="status">
    Workspace ready for <strong x-text="name"></strong>!
  </p>
</form>

Adding novalidate lets your Alpine validation messages take over cleanly in the browser while your backend still validates the real POST request on the server.

Five everyday Alpine.js components in ten lines each

Alpine shines when you want crisp interactive widgets right inside server-rendered HTML with zero build step. Here are five small patterns you can drop into any page today.

1. Dropdown menu that closes on outside click

<div x-data="{ open: false }" @click.outside="open = false">
  <button type="button" @click="open = !open">Menu</button>
  <ul x-show="open" x-cloak>
    <li><a href="/profile">Profile</a></li>
    <li><a href="/settings">Settings</a></li>
  </ul>
</div>

2. Simple tabs switcher

<div x-data="{ tab: 'html' }">
  <button type="button" @click="tab = 'html'">HTML</button>
  <button type="button" @click="tab = 'css'">CSS</button>

  <p x-show="tab === 'html'">Structure your page with semantic tags.</p>
  <p x-show="tab === 'css'" x-cloak>Style your layout with Grid and Flex.</p>
</div>

3. Copy-to-clipboard button with feedback

<div x-data="{ copied: false }">
  <button
    type="button"
    @click="navigator.clipboard.writeText('npm install alpinejs');
      copied = true;
      setTimeout(() => copied = false, 1500)"
    x-text="copied ? 'Copied!' : 'Copy command'"
  ></button>
</div>

4. Live character counter

<div x-data="{ bio: '' }">
  <textarea x-model="bio" maxlength="160"></textarea>
  <p><span x-text="160 - bio.length"></span> characters left</p>
</div>

5. Show/hide password toggle

<div x-data="{ show: false }">
  <input :type="show ? 'text' : 'password'" name="password">
  <button type="button" @click="show = !show"
    x-text="show ? 'Hide' : 'Show'"></button>
</div>

Lifecycle hooks and magic properties

As your components grow past simple toggles, Alpine’s lifecycle hooks and $-prefixed magic properties give you clean access to the DOM without spaghetti document.querySelector code.

x-init and x-effect

  • x-init runs once when Alpine initializes the element. Use it to read URL params, start a timer, or fetch initial data.
  • x-effect runs immediately and then automatically re-runs whenever any reactive property referenced inside it changes!
<div
  x-data="{ theme: 'light' }"
  x-effect="document.documentElement.dataset.theme = theme"
>
  <button @click="theme = theme === 'light' ? 'dark' : 'light'">
    Theme: <span x-text="theme"></span>
  </button>
</div>

$refs and $nextTick

Mark any element with x-ref="searchInput" and reference it inside your component via $refs.searchInput.

Combine $refs with $nextTick() whenever you reveal an element with x-show and immediately want to focus it (because a hidden display: none input cannot receive focus until Alpine updates the DOM on the next tick):

<div x-data="{ open: false }">
  <button @click="open = true; $nextTick(() => $refs.searchInput.focus())">
    Search
  </button>

  <input x-show="open" x-cloak x-ref="searchInput" type="search" />
</div>

$watch and $id

  • $watch('query', (newVal, oldVal) => ...) runs a callback whenever a specific property changes (including nested paths like 'user.email').
  • $id('input-name') (paired with x-id="['input-name']") generates guaranteed-unique HTML IDs per component instance so rendering the same component three times on a page never produces duplicate id attributes:
<div x-data x-id="['email-field']">
  <label :for="$id('email-field')">Email</label>
  <input :id="$id('email-field')" type="email" />
</div>

Fetching data and async state in Alpine

Although I prefer htmx for full HTML server updates, sometimes you genuinely want to fetch a small JSON endpoint from Alpine (like live GitHub stars, search suggestions, or exchange rates).

Track three explicit states (loading, error, and items) and cancel overlapping requests with AbortController so stale responses never overwrite newer ones:

document.addEventListener('alpine:init', () => {
  Alpine.data('bookSearch', () => ({
    query: '',
    items: [],
    loading: false,
    error: '',
    controller: null,

    async search() {
      const q = this.query.trim()
      if (!q) {
        this.items = []
        this.error = ''
        return
      }

      this.controller?.abort()
      this.controller = new AbortController()
      this.loading = true
      this.error = ''

      try {
        const res = await fetch(`/api/books?q=${encodeURIComponent(q)}`, {
          signal: this.controller.signal,
        })
        if (!res.ok) throw new Error(`HTTP ${res.status}`)
        this.items = await res.json()
      } catch (err) {
        if (err.name !== 'AbortError') {
          this.error = 'Could not load results. Try again.'
        }
      } finally {
        this.loading = false
      }
    },

    destroy() {
      this.controller?.abort()
    },
  }))
})

Notice destroy() automatically aborts any in-flight fetch if the component gets removed from the page.

Reusable components with Alpine.data() and Alpine.bind()

Inline x-data="{ open: false }" is wonderful for two-line toggles. Once a component grows past five lines of logic (or appears on multiple pages), move the JavaScript out of your HTML using Alpine.data().

Register the component inside an alpine:init listener (when using CDN) or before Alpine.start() (when using npm):

document.addEventListener('alpine:init', () => {
  Alpine.data('dropdown', (initialOpen = false) => ({
    open: initialOpen,

    init() {
      // Runs automatically when mounted
    },

    toggle() {
      this.open = !this.open
    },

    close() {
      this.open = false
    },

    destroy() {
      // Clean up timers or window listeners here
    },
  }))
})

Now your HTML stays clean and readable everywhere you reuse it:

<div x-data="dropdown(false)" @click.outside="close()" @keydown.escape.window="close()">
  <button type="button" @click="toggle()" :aria-expanded="open">Options</button>
  <div x-show="open" x-transition x-cloak>
    <a href="/settings">Settings</a>
    <a href="/logout">Sign out</a>
  </div>
</div>

You can also bundle reusable directive sets with Alpine.bind() and apply them with x-bind="trigger" when several elements share identical accessibility attributes and event handlers.

Sharing global state with Alpine.store() and $dispatch

When two unrelated parts of the page need to share state (for example, a navbar toast banner, a slide-over cart drawer, or a global dark-mode toggle), register a reactive store with Alpine.store().

Product card@click='$store.toast.show(...)'Alpine.store('toast')(Global reactivestate)Navbar toast bannerx-show='$store.toast.visible'

Define the store once inside alpine:init:

document.addEventListener('alpine:init', () => {
  Alpine.store('toast', {
    message: '',
    visible: false,
    timer: null,

    show(text, duration = 3000) {
      this.message = text
      this.visible = true
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.visible = false
      }, duration)
    },

    hide() {
      clearTimeout(this.timer)
      this.visible = false
    },
  })
})

Read or call it from any Alpine component via $store.toast (or even from regular vanilla JavaScript via Alpine.store('toast').show('Done!')):

<button x-data @click="$store.toast.show('Saved to favorites!')">
  Favorite
</button>

<div
  x-data
  x-show="$store.toast.visible"
  x-transition
  x-cloak
  role="status"
  aria-live="polite"
>
  <span x-text="$store.toast.message"></span>
  <button type="button" @click="$store.toast.hide()" aria-label="Dismiss">x</button>
</div>

For loose one-way child-to-parent communication without a global store, dispatch a custom DOM event with $dispatch('notify', { text: 'Copied!' }) and listen anywhere up the tree or on window with @notify.window="handleNotify($event.detail.text)".

Escaping layout traps with x-teleport and x-modelable

Once we build modals, tooltips, and reusable form inputs in real apps, we quickly run into two classic UI headaches: clipped overlays and custom inputs that need two-way binding.

Alpine solves both cleanly with two built-in directives.

Rendering modals cleanly with x-teleport

Have you ever opened a modal or popover inside a card that has overflow: hidden or a CSS transform, only to see your modal sliced in half?

That happens because overflow: hidden and transform trap position: fixed descendants inside that card’s stacking context.

Wrap your modal inside <template x-teleport="body"> and Alpine physically moves the rendered DOM node to the end of <body>, while keeping it wired directly to your component’s x-data scope:

<div x-data="{ open: false }" class="card overflow-hidden">
  <button type="button" @click="open = true">Open modal</button>

  <template x-teleport="body">
    <div
      x-show="open"
      x-transition.opacity
      x-cloak
      @click.self="open = false"
      @keydown.escape.window="open = false"
      role="dialog"
      aria-modal="true"
      class="fixed inset-0 z-50 grid place-items-center bg-black/50"
    >
      <div class="rounded-xl bg-white p-6 shadow-xl">
        <h2>Still reads parent state!</h2>
        <button type="button" @click="open = false">Close</button>
      </div>
    </div>
  </template>
</div>

Notice we still toggle open = false right inside the teleported dialog without needing a global store or $dispatch. Like x-if and x-for, <template x-teleport="body"> must contain one single root element.

Building custom x-model components with x-modelable

Suppose we build a reusable 5-star rating widget or custom toggle switch, and we want any parent form to bind to it with regular x-model="rating".

Expose any internal property to parent x-model bindings using x-modelable:

<form x-data="{ rating: 4 }">
  <div
    x-data="{ stars: 0 }"
    x-modelable="stars"
    x-model="rating"
    role="radiogroup"
    aria-label="Rating"
  >
    <template x-for="n in 5" :key="n">
      <button
        type="button"
        @click="stars = n"
        :aria-checked="stars === n"
        x-text="n <= stars ? '★' : '☆'"
      ></button>
    </template>
  </div>

  <p>Parent rating: <strong x-text="rating"></strong> / 5</p>
</form>

Clicking star 3 updates stars inside the child, which immediately updates rating in the parent form, and changing rating from the parent updates the stars right back!

Custom directives and magic properties (Alpine.directive and Alpine.magic)

Most of the time, Alpine.data() covers our reusable logic. When we find ourselves repeating the same small DOM utility or helper across ten unrelated components, we can extend Alpine itself with Alpine.magic() and Alpine.directive().

Writing a custom magic property ($formatMoney)

Register custom magics inside alpine:init (or before Alpine.start()):

document.addEventListener('alpine:init', () => {
  Alpine.magic('formatMoney', () => {
    return (cents, currency = 'USD') =>
      new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency,
      }).format(cents / 100)
  })
})

Now any component on the page can format prices in one expression:

<div x-data="{ priceCents: 2900 }">
  <span x-text="$formatMoney(priceCents)"></span>
</div>

Writing a custom directive (x-auto-resize)

Custom directives let us attach reusable DOM behavior directly to HTML elements, complete with a cleanup() callback when the element leaves the page:

document.addEventListener('alpine:init', () => {
  Alpine.directive('auto-resize', (el, _meta, { cleanup }) => {
    const resize = () => {
      el.style.height = 'auto'
      el.style.height = `${el.scrollHeight}px`
    }

    el.addEventListener('input', resize)
    resize()

    cleanup(() => {
      el.removeEventListener('input', resize)
    })
  })
})

Now any <textarea x-data x-auto-resize></textarea> grows smoothly as the user types, and automatically removes its event listener if htmx or x-if removes the textarea later!

Form validation, optimistic UI, and image previews

Alpine is awesome for making everyday forms feel responsive without replacing normal server-side validation.

Live field feedback with dirty tracking

Instead of yelling red errors on page load, track whether the user has touched each input (touched.email) before showing inline feedback:

<form
  x-data="{
    email: '',
    password: '',
    touched: { email: false, password: false },
    get emailError() {
      if (!this.touched.email) return ''
      return this.email.includes('@') ? '' : 'Enter a valid email address.'
    },
    get passwordScore() {
      let score = 0
      if (this.password.length >= 12) score++
      if (/[A-Z]/.test(this.password)) score++
      if (/[0-9]/.test(this.password)) score++
      return score
    },
    get canSubmit() {
      return this.email.includes('@') && this.password.length >= 12
    }
  }"
  action="/signup"
  method="POST"
>
  <label for="signup-email">Email</label>
  <input
    id="signup-email"
    name="email"
    type="email"
    x-model.trim="email"
    @blur="touched.email = true"
    :aria-invalid="Boolean(emailError)"
    required
  />
  <p x-show="emailError" x-text="emailError" role="alert"></p>

  <label for="signup-pw">Password (12+ chars)</label>
  <input
    id="signup-pw"
    name="password"
    type="password"
    x-model="password"
    @blur="touched.password = true"
    required
  />
  <p>Strength: <strong x-text="['Weak', 'Fair', 'Good', 'Strong'][passwordScore]"></strong></p>

  <button type="submit" :disabled="!canSubmit">Create account</button>
</form>

Optimistic UI updates with automatic rollback

When a user clicks a Like or Bookmark button, waiting 300 ms for the server makes the UI feel sluggish.

Update the state immediately, fire fetch(), and roll back cleanly if the server rejects the request:

document.addEventListener('alpine:init', () => {
  Alpine.data('bookmarkButton', (postId, initialSaved) => ({
    saved: initialSaved,
    busy: false,

    async toggle() {
      if (this.busy) return
      const previous = this.saved
      this.saved = !previous
      this.busy = true

      try {
        const res = await fetch(`/api/posts/${postId}/bookmark`, {
          method: this.saved ? 'POST' : 'DELETE',
        })
        if (!res.ok) throw new Error('Request failed')
      } catch {
        this.saved = previous
        Alpine.store('toast')?.show('Could not update bookmark. Try again.')
      } finally {
        this.busy = false
      }
    },
  }))
})

Instant image upload preview with memory cleanup

Let users see their chosen avatar before submitting the form, and revoke the temporary blob URL when they pick a different file or leave the page:

<div
  x-data="{
    previewUrl: null,
    onPick(event) {
      const file = event.target.files?.[0]
      if (!file) return
      if (this.previewUrl) URL.revokeObjectURL(this.previewUrl)
      this.previewUrl = URL.createObjectURL(file)
    },
    destroy() {
      if (this.previewUrl) URL.revokeObjectURL(this.previewUrl)
    }
  }"
>
  <input type="file" name="avatar" accept="image/png,image/jpeg" @change="onPick($event)" />
  <img x-show="previewUrl" x-cloak :src="previewUrl" alt="Selected preview" width="96" height="96" />
</div>

Official Alpine plugins

Alpine stays tiny (~15 KB gzipped) because specialized features live in small official plugins you add only when a page needs them:

PluginDirective / MagicWhat it solves
@alpinejs/persist$persist(val)Syncs state to localStorage across reloads
@alpinejs/focusx-trap, $focusTraps Tab focus inside modals and menus
@alpinejs/collapsex-collapseAnimates height between 0 and auto
@alpinejs/intersectx-intersectRuns code when elements enter the viewport
@alpinejs/maskx-maskFormats dates, phones, and numbers on type
@alpinejs/anchorx-anchorPositions popovers near a trigger button

Load order matters. When using a CDN, place every plugin <script defer> tag before the core alpinejs script:

<script
  defer
  src="https://unpkg.com/@alpinejs/persist@3.17.6/dist/cdn.min.js"
></script>
<script
  defer
  src="https://unpkg.com/@alpinejs/focus@3.17.6/dist/cdn.min.js"
></script>
<script
  defer
  src="https://unpkg.com/@alpinejs/collapse@3.17.6/dist/cdn.min.js"
></script>
<script
  defer
  src="https://unpkg.com/@alpinejs/intersect@3.17.6/dist/cdn.min.js"
></script>
<script
  defer
  src="https://unpkg.com/alpinejs@3.17.6/dist/cdn.min.js"
></script>

When bundling with npm and Vite, register every plugin with Alpine.plugin() before calling Alpine.start():

import Alpine from 'alpinejs'
import anchor from '@alpinejs/anchor'
import collapse from '@alpinejs/collapse'
import focus from '@alpinejs/focus'
import intersect from '@alpinejs/intersect'
import mask from '@alpinejs/mask'
import persist from '@alpinejs/persist'

Alpine.plugin(persist)
Alpine.plugin(focus)
Alpine.plugin(collapse)
Alpine.plugin(intersect)
Alpine.plugin(mask)
Alpine.plugin(anchor)
Alpine.start()

Let’s look at practical examples of the four plugins I reach for most often, plus mask and anchor.

Saving state in localStorage with @alpinejs/persist

Wrap any default value inside $persist(...) and Alpine saves changes to localStorage and restores them on page reload.

Give each value an explicit storage key with .as('my-key') so two pages on the same domain never collide. Pass .using(sessionStorage) when you want the value cleared as soon as the tab closes.

Here is a draft note editor that never loses your typing if you refresh the tab:

<div
  x-data="{
    sidebar: $persist(true).as('app-sidebar'),
    draft: $persist('').as('note-draft').using(sessionStorage)
  }"
>
  <button type="button" @click="sidebar = !sidebar">
    <span x-text="sidebar ? 'Hide sidebar' : 'Show sidebar'"></span>
  </button>

  <textarea
    x-model="draft"
    rows="4"
    placeholder="Start typing, then reload this tab..."
  ></textarea>

  <button type="button" @click="draft = ''">Clear draft</button>
</div>

$persist handles booleans, numbers, strings, arrays, and plain objects through JSON serialization.

Locking keyboard focus with @alpinejs/focus

Accessible modals need keyboard Tab navigation to stay trapped inside the open dialog, and focus should jump back to the trigger button when the modal closes.

Add x-trap.noscroll.inert="open" on your dialog container. The .noscroll modifier freezes background page scrolling, and .inert marks everything outside the modal inert so screen readers stay inside the dialog:

<div x-data="{ open: false }">
  <button type="button" @click="open = true">Open modal</button>

  <div
    x-show="open"
    x-trap.noscroll.inert="open"
    @keydown.escape.window="open = false"
    role="dialog"
    aria-modal="true"
    x-cloak
  >
    <h2>Confirm action</h2>
    <input type="text" placeholder="Type DELETE to confirm" />
    <button type="button" @click="open = false">Cancel</button>
  </div>
</div>

The focus plugin also exposes a $focus magic helper. You can wire arrow-key navigation inside any menu or toolbar in two attributes:

<div
  x-data
  @keydown.arrow-down.prevent="$focus.wrap().next()"
  @keydown.arrow-up.prevent="$focus.wrap().previous()"
>
  <button type="button">Edit</button>
  <button type="button">Duplicate</button>
  <button type="button">Archive</button>
</div>

Adding .wrap() cycles from the last button back to the first when the user presses Arrow Down.

Animating height with @alpinejs/collapse

CSS cannot smoothly animate height from 0 to auto on its own. Adding x-collapse beside x-show measures the real height and animates it smoothly:

<div x-data="{ open: false }">
  <button
    type="button"
    @click="open = !open"
    :aria-expanded="open"
  >
    Shipping details
  </button>

  <div x-show="open" x-collapse.duration.250ms x-cloak>
    <p>Orders ship within 24 hours with tracking included.</p>
  </div>
</div>

You can also pass .min.48px to create a “Read more” preview card that collapses down to a 48-pixel teaser instead of hiding completely:

<div x-data="{ expanded: false }">
  <div x-show="expanded" x-collapse.min.48px>
    <p>
      Alpine lets you add interactive widgets right inside HTML.
      With the collapse plugin, long product descriptions can
      stay compact until a visitor clicks to read the full text.
    </p>
  </div>

  <button type="button" @click="expanded = !expanded">
    <span x-text="expanded ? 'Show less' : 'Read more'"></span>
  </button>
</div>

Running code on scroll with @alpinejs/intersect

@alpinejs/intersect wraps the browser’s IntersectionObserver API in one directive.

Use x-intersect.once to trigger a scroll-in animation once, or split enter and leave behavior with x-intersect:enter and x-intersect:leave. Modifiers like .half, .full, and .margin.100px control how much of the element must be visible before firing:

<section
  x-data="{ shown: false }"
  x-intersect.once.half="shown = true"
>
  <div x-show="shown" x-transition.duration.400ms x-cloak>
    <h2>Fades in once when half visible</h2>
  </div>
</section>

You can also place an invisible sentinel at the bottom of a feed to load the next page right before the reader reaches the footer:

<div
  x-data="{
    page: 1,
    items: ['Post 1', 'Post 2', 'Post 3'],
    loadMore() {
      this.page++
      const base = (this.page - 1) * 3
      this.items.push(
        `Post ${base + 1}`,
        `Post ${base + 2}`,
        `Post ${base + 3}`
      )
    }
  }"
>
  <ul>
    <template x-for="item in items" :key="item">
      <li x-text="item"></li>
    </template>
  </ul>

  <div x-intersect.margin.120px="loadMore()">
    Loading more posts...
  </div>
</div>

Input masks and smart popovers (@alpinejs/mask and @alpinejs/anchor)

Format structured inputs as the visitor types with x-mask (9 matches a digit, a matches a letter, * matches either):

<input
  type="text"
  x-data
  x-mask="99/99/9999"
  placeholder="MM/DD/YYYY"
/>

And position dropdowns or tooltips beside a trigger button with x-anchor, which flips the menu above the button if there is no room left at the bottom of the screen:

<div x-data="{ open: false }" @click.outside="open = false">
  <button type="button" x-ref="btn" @click="open = !open">
    Actions
  </button>

  <ul
    x-show="open"
    x-anchor.bottom-start.offset.6="$refs.btn"
    x-trap="open"
    x-cloak
  >
    <li><button type="button">Duplicate</button></li>
    <li><button type="button">Archive</button></li>
  </ul>
</div>

Pairing Alpine.js with htmx and server-rendered apps

Alpine.js and htmx are a match made in heaven because each tool handles a completely different job.

No (dropdown, tabs,modal)Yes (save, search,delete)HX-Trigger headerUser actionNeeds serverdata?Alpine.js handles itinstantly in memoryhtmx sends HTTPrequest& swaps HTMLfragment

Keep one clear boundary rule:

  • htmx owns server round-trips and HTML swaps (saving forms, loading filtered lists, deleting rows, pagination).
  • Alpine owns ephemeral browser-only UI state (is the modal open, which tab is active, live character counts, copy-to-clipboard feedback, toast banners).

Your server can trigger Alpine directly from any htmx response using the HX-Trigger HTTP header:

HX-Trigger: {"toast": "Project saved!"}

Listen on window in Alpine:

<div x-data @toast.window="$store.toast.show($event.detail.value)"></div>

And you can close an Alpine modal automatically right after an htmx form inside it succeeds:

<form
  hx-post="/projects"
  hx-target="#project-list"
  hx-swap="beforeend"
  @htmx:after-request="if ($event.detail.successful) open = false"
>
  ...
</form>

Keep long-lived UI state (like toasts or sidebar drawers) outside elements that htmx swaps, or inside Alpine.store(), so swapping a fragment never resets them.

Six copy-and-paste UI components in plain HTML and Alpine 3

Most websites reuse the same handful of interactive widgets over and over.

Here are six complete, accessible components written in plain HTML, minimal CSS, and Alpine 3. Drop any of them into an HTML file with Alpine loaded and they work right away.

1. Accessible dropdown menu with Escape and @click.outside

A solid dropdown opens on click, closes when the user clicks outside or presses Escape, updates aria-expanded, and sends focus back to the trigger button when dismissed with the keyboard:

<style>
  .menu-wrap { position: relative; display: inline-block; }
  .menu-list {
    position: absolute;
    top: calc(100% + 6px);
    left: 0;
    min-width: 11rem;
    margin: 0;
    padding: 0.35rem;
    list-style: none;
    background: #ffffff;
    border: 1px solid #cbd5e1;
    border-radius: 0.5rem;
    box-shadow: 0 8px 20px rgba(15, 23, 42, 0.08);
  }
  .menu-list a,
  .menu-list button {
    display: block;
    width: 100%;
    text-align: left;
    padding: 0.45rem 0.65rem;
    border: 0;
    background: transparent;
    color: #0f172a;
    text-decoration: none;
    cursor: pointer;
  }
</style>

<div
  class="menu-wrap"
  x-data="{
    open: false,
    close(refocus = false) {
      if (!this.open) return
      this.open = false
      if (refocus) {
        this.$nextTick(() => this.$refs.trigger.focus())
      }
    }
  }"
  @click.outside="close(false)"
  @keydown.escape.window="close(true)"
>
  <button
    type="button"
    x-ref="trigger"
    @click="open = !open"
    aria-haspopup="menu"
    :aria-expanded="open"
  >
    Account menu
  </button>

  <ul
    class="menu-list"
    role="menu"
    x-show="open"
    x-transition.origin.top.left
    x-cloak
  >
    <li role="none"><a role="menuitem" href="/profile">Profile</a></li>
    <li role="none"><a role="menuitem" href="/billing">Billing</a></li>
    <li role="none">
      <button type="button" role="menuitem" @click="close(true)">
        Sign out
      </button>
    </li>
  </ul>
</div>

2. Accordion FAQ

Store the currently open item ID in active so opening one question closes the previous one. Using $id('faq') guarantees unique aria-controls IDs even if you put two accordions on the same page:

<style>
  .faq-item {
    border-bottom: 1px solid #e2e8f0;
    padding: 0.75rem 0;
  }
  .faq-btn {
    width: 100%;
    display: flex;
    justify-content: space-between;
    background: none;
    border: 0;
    font: inherit;
    font-weight: 600;
    cursor: pointer;
    text-align: left;
  }
</style>

<div
  x-data="{
    active: 1,
    faqs: [
      {
        id: 1,
        q: 'Do I need a bundler for Alpine?',
        a: 'No. Add one deferred script tag and start writing HTML.'
      },
      {
        id: 2,
        q: 'Does Alpine work with htmx?',
        a: 'Yes. htmx swaps server HTML and Alpine handles local UI.'
      },
      {
        id: 3,
        q: 'Can I animate accordion height?',
        a: 'Yes. Load @alpinejs/collapse and add x-collapse.'
      }
    ],
    toggle(id) {
      this.active = this.active === id ? null : id
    }
  }"
>
  <template x-for="item in faqs" :key="item.id">
    <div class="faq-item" x-id="['faq-panel']">
      <h3>
        <button
          type="button"
          class="faq-btn"
          @click="toggle(item.id)"
          :aria-expanded="active === item.id"
          :aria-controls="$id('faq-panel')"
        >
          <span x-text="item.q"></span>
          <span x-text="active === item.id ? '-' : '+'"></span>
        </button>
      </h3>

      <div
        :id="$id('faq-panel')"
        x-show="active === item.id"
        x-transition
        x-cloak
      >
        <p x-text="item.a"></p>
      </div>
    </div>
  </template>
</div>

If you want visitors to keep multiple answers open at once, change active: 1 to an array openIds: [1] and toggle membership in that array.

3. Modal dialog with x-trap

Load @alpinejs/focus before core Alpine so x-trap.noscroll.inert="open" locks Tab focus inside the modal and freezes page scroll. Wrapping the dialog in <template x-teleport="body"> keeps it safe from overflow: hidden parent cards:

<style>
  .backdrop {
    position: fixed;
    inset: 0;
    z-index: 50;
    display: grid;
    place-items: center;
    background: rgba(15, 23, 42, 0.55);
  }
  .dialog {
    background: #ffffff;
    padding: 1.5rem;
    border-radius: 0.75rem;
    max-width: 24rem;
    width: 90%;
  }
</style>

<div
  x-data="{
    open: false,
    openModal() {
      this.open = true
    },
    closeModal() {
      this.open = false
      this.$nextTick(() => this.$refs.openBtn.focus())
    }
  }"
  @keydown.escape.window="if (open) closeModal()"
>
  <button type="button" x-ref="openBtn" @click="openModal()">
    Delete project
  </button>

  <template x-teleport="body">
    <div
      class="backdrop"
      x-show="open"
      x-transition.opacity
      x-cloak
      @click.self="closeModal()"
      role="dialog"
      aria-modal="true"
      aria-labelledby="modal-heading"
    >
      <div class="dialog" x-trap.noscroll.inert="open">
        <h2 id="modal-heading">Delete project?</h2>
        <p>This action cannot be undone.</p>
        <button type="button" @click="closeModal()">Cancel</button>
        <button type="button" @click="closeModal()">
          Confirm delete
        </button>
      </div>
    </div>
  </template>
</div>

Notice @click.self="closeModal()" on the backdrop. Clicking the dark overlay closes the modal, while clicking inside .dialog leaves it open.

4. Toast notification bus with $dispatch and @notify.window

You do not need a global store just to show toast alerts from anywhere on a page.

Drop one toast listener near the end of <body> listening for @notify.window, then fire $dispatch('notify', { message, type }) from any button or component on the page:

<style>
  .toast-stack {
    position: fixed;
    bottom: 1rem;
    right: 1rem;
    display: grid;
    gap: 0.5rem;
    z-index: 60;
  }
  .toast-item {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    padding: 0.65rem 1rem;
    border-radius: 0.5rem;
    color: #ffffff;
    background: #0f172a;
  }
  .toast-item.success { background: #15803d; }
  .toast-item.error { background: #b91c1c; }
</style>

<div x-data>
  <button
    type="button"
    @click="$dispatch('notify', {
      message: 'Settings saved.',
      type: 'success'
    })"
  >
    Save settings
  </button>

  <button
    type="button"
    @click="$dispatch('notify', {
      message: 'Upload failed. Try again.',
      type: 'error'
    })"
  >
    Trigger error
  </button>
</div>

<div
  class="toast-stack"
  role="status"
  aria-live="polite"
  x-data="{
    toasts: [],
    add(detail) {
      const id = Date.now() + Math.random()
      this.toasts.push({
        id,
        message: detail.message,
        type: detail.type || 'info'
      })
      setTimeout(() => this.remove(id), 3500)
    },
    remove(id) {
      this.toasts = this.toasts.filter((t) => t.id !== id)
    }
  }"
  @notify.window="add($event.detail)"
>
  <template x-for="t in toasts" :key="t.id">
    <div class="toast-item" :class="t.type" x-transition>
      <span x-text="t.message"></span>
      <button
        type="button"
        @click="remove(t.id)"
        aria-label="Dismiss"
      >
        x
      </button>
    </div>
  </template>
</div>

Because each toast gets its own id and timeout, rapid clicks stack nicely and disappear in order.

5. Character counter and copy-to-clipboard button

Combine a live character counter with a copy-to-clipboard button for social posts, invite snippets, or support replies:

<div
  x-data="{
    text: '',
    limit: 280,
    status: 'Copy text',
    get remaining() {
      return this.limit - this.text.length
    },
    get overLimit() {
      return this.remaining < 0
    },
    async copyText() {
      if (!this.text.trim() || this.overLimit) return
      try {
        await navigator.clipboard.writeText(this.text)
        this.status = 'Copied!'
      } catch {
        this.status = 'Copy blocked'
      }
      setTimeout(() => (this.status = 'Copy text'), 1800)
    }
  }"
>
  <label for="post-box">Shareable snippet</label>
  <textarea
    id="post-box"
    x-model="text"
    rows="4"
    placeholder="Write up to 280 characters..."
  ></textarea>

  <p
    :style="{
      color: overLimit
        ? '#b91c1c'
        : remaining <= 25 ? '#b45309' : '#334155'
    }"
  >
    <strong x-text="remaining"></strong> characters remaining
  </p>

  <button
    type="button"
    @click="copyText()"
    :disabled="!text.trim() || overLimit"
    x-text="status"
  ></button>
</div>

Notice we wrap navigator.clipboard.writeText() in try/catch, because browsers require HTTPS (or localhost) for clipboard writes and reject the call on insecure pages.

6. Multi-step wizard form

Split long onboarding forms into three steps while keeping every <input> inside the same <form> with x-show. Because x-show leaves hidden steps in the DOM, the browser submits every field on step 3 without losing earlier answers:

<form
  x-data="{
    step: 1,
    name: '',
    email: '',
    plan: 'pro',
    extras: [],
    error: '',
    next() {
      this.error = ''
      if (this.step === 1) {
        if (!this.name.trim() || !this.email.includes('@')) {
          this.error = 'Enter your name and a valid email.'
          return
        }
      }
      if (this.step < 3) this.step++
    },
    back() {
      this.error = ''
      if (this.step > 1) this.step--
    }
  }"
  action="/onboarding"
  method="POST"
>
  <p>Step <strong x-text="step"></strong> of 3</p>
  <p x-show="error" x-text="error" role="alert"></p>

  <fieldset x-show="step === 1">
    <legend>1. Account details</legend>
    <input
      name="name"
      x-model.trim="name"
      placeholder="Full name"
      required
    />
    <input
      name="email"
      type="email"
      x-model.trim="email"
      placeholder="Email address"
      required
    />
  </fieldset>

  <fieldset x-show="step === 2" x-cloak>
    <legend>2. Plan and add-ons</legend>
    <label>
      <input type="radio" name="plan" value="free" x-model="plan" />
      Free
    </label>
    <label>
      <input type="radio" name="plan" value="pro" x-model="plan" />
      Pro
    </label>
    <label>
      <input
        type="checkbox"
        name="extras[]"
        value="backups"
        x-model="extras"
      />
      Daily backups
    </label>
    <label>
      <input
        type="checkbox"
        name="extras[]"
        value="support"
        x-model="extras"
      />
      Priority support
    </label>
  </fieldset>

  <fieldset x-show="step === 3" x-cloak>
    <legend>3. Review and confirm</legend>
    <p>Name: <strong x-text="name"></strong></p>
    <p>Email: <strong x-text="email"></strong></p>
    <p>Plan: <strong x-text="plan"></strong></p>
    <p>
      Add-ons:
      <strong x-text="extras.join(', ') || 'None'"></strong>
    </p>
  </fieldset>

  <div>
    <button type="button" x-show="step > 1" @click="back()">
      Back
    </button>
    <button type="button" x-show="step < 3" @click="next()">
      Continue
    </button>
    <button type="submit" x-show="step === 3" x-cloak>
      Finish setup
    </button>
  </div>
</form>

Advanced interactive widgets

Once you are comfortable with those six building blocks, you can combine keyboard shortcuts, teleported overlays, and x-effect to build richer desktop-style interfaces.

1. Keyboard-friendly tabs

<div x-data="{ tab: 'overview' }">
  <div role="tablist" aria-label="Product sections">
    <button
      type="button"
      role="tab"
      :aria-selected="tab === 'overview'"
      @click="tab = 'overview'"
    >
      Overview
    </button>
    <button
      type="button"
      role="tab"
      :aria-selected="tab === 'pricing'"
      @click="tab = 'pricing'"
    >
      Pricing
    </button>
  </div>

  <div role="tabpanel" x-show="tab === 'overview'">
    Overview details go here.
  </div>
  <div role="tabpanel" x-show="tab === 'pricing'" x-cloak>
    Pricing plans go here.
  </div>
</div>

2. Keyboard Command Palette (Cmd+K)

Users love quick keyboard navigation. This command palette opens with Cmd+K or Ctrl+K, filters commands live, moves highlight with ArrowDown and ArrowUp, and navigates on Enter:

<div
  x-data="{
    open: false,
    query: '',
    activeIndex: 0,
    commands: [
      { label: 'Go to Dashboard', href: '/dashboard' },
      { label: 'Billing Settings', href: '/billing' },
      { label: 'API Keys', href: '/keys' },
      { label: 'Documentation', href: '/docs' }
    ],
    get matches() {
      const q = this.query.trim().toLowerCase()
      return q
        ? this.commands.filter((c) =>
            c.label.toLowerCase().includes(q)
          )
        : this.commands
    },
    openPalette() {
      this.open = true
      this.query = ''
      this.activeIndex = 0
      this.$nextTick(() => this.$refs.cmdInput.focus())
    },
    move(delta) {
      if (!this.matches.length) return
      const len = this.matches.length
      this.activeIndex = (this.activeIndex + delta + len) % len
    },
    runActive() {
      const item = this.matches[this.activeIndex]
      if (item) window.location.href = item.href
    }
  }"
  @keydown.cmd.k.window.prevent="openPalette()"
  @keydown.ctrl.k.window.prevent="openPalette()"
  @keydown.escape.window="open = false"
>
  <button type="button" @click="openPalette()">
    Quick Jump (Cmd+K)
  </button>

  <template x-teleport="body">
    <div
      x-show="open"
      x-cloak
      @click.self="open = false"
      role="dialog"
      aria-modal="true"
    >
      <div>
        <input
          x-ref="cmdInput"
          type="search"
          x-model="query"
          @input="activeIndex = 0"
          @keydown.arrow-down.prevent="move(1)"
          @keydown.arrow-up.prevent="move(-1)"
          @keydown.enter.prevent="runActive()"
          placeholder="Type a command..."
        />
        <ul role="listbox">
          <template x-for="(cmd, idx) in matches" :key="cmd.href">
            <li
              role="option"
              :aria-selected="idx === activeIndex"
              @mouseenter="activeIndex = idx"
              @click="runActive()"
              x-text="cmd.label"
            ></li>
          </template>
        </ul>
      </div>
    </div>
  </template>
</div>

3. Sortable data table with bulk selection

Notice how x-effect updates the master checkbox’s .indeterminate property when only some rows are selected:

<div
  x-data="{
    selected: [],
    rows: [
      { id: 101, customer: 'Elena', amount: 49 },
      { id: 102, customer: 'Marco', amount: 129 },
      { id: 103, customer: 'Sofia', amount: 29 }
    ],
    get allSelected() {
      return (
        this.rows.length > 0 &&
        this.selected.length === this.rows.length
      )
    },
    toggleAll(checked) {
      this.selected = checked
        ? this.rows.map((r) => String(r.id))
        : []
    }
  }"
>
  <p x-show="selected.length > 0" x-cloak>
    <strong x-text="selected.length"></strong> selected
    <button type="button" @click="selected = []">Clear</button>
  </p>

  <table>
    <thead>
      <tr>
        <th>
          <input
            type="checkbox"
            :checked="allSelected"
            x-effect="
              $el.indeterminate =
                selected.length > 0 && !allSelected
            "
            @change="toggleAll($event.target.checked)"
            aria-label="Select all rows"
          />
        </th>
        <th>Customer</th>
        <th>Amount</th>
      </tr>
    </thead>
    <tbody>
      <template x-for="row in rows" :key="row.id">
        <tr>
          <td>
            <input
              type="checkbox"
              :value="String(row.id)"
              x-model="selected"
            />
          </td>
          <td x-text="row.customer"></td>
          <td>$<span x-text="row.amount"></span></td>
        </tr>
      </template>
    </tbody>
  </table>
</div>

Performance, Alpine.raw(), and Astro View Transitions

Alpine is fast by default because it only wraps properties you declare inside x-data. Still, a few practical habits keep larger pages snappy and leak-free.

Keep third-party instances out of reactive Proxies

Suppose you initialize a Chart.js graph, Leaflet map, or CodeMirror editor inside an Alpine.data() component.

If you store this.chart = new Chart(...) directly on reactive x-data, Alpine wraps that massive third-party object in a JavaScript Proxy, which can cause strange errors or slow down canvas redraws!

Store non-reactive third-party instances in a closure variable inside your Alpine.data() factory instead of on this:

Alpine.data('revenueChart', (points) => {
  let chartInstance = null

  return {
    init() {
      chartInstance = new Chart(this.$refs.canvas, {
        type: 'bar',
        data: Alpine.raw(points),
      })
    },
    destroy() {
      chartInstance?.destroy()
      chartInstance = null
    },
  }
})

Passing Alpine.raw(points) strips the reactive Proxy wrapper before handing an array to external libraries (or printing it cleanly in console.log).

Cleaning up timers and global listeners

Whenever an init() method creates a setInterval, ResizeObserver, or window.addEventListener, save its handle and tear it down inside destroy(). Alpine invokes destroy() automatically when a component is removed by x-if, x-for, or an htmx swap.

Using Alpine with Astro View Transitions (<ClientRouter />)

When you pair Alpine with Astro’s <ClientRouter />, Astro swaps the page DOM during client-side navigation. Register your Alpine.data() and Alpine.store() definitions once at module load or inside alpine:init, and let Alpine automatically observe new x-data nodes added to document.body. If you initialize Alpine via npm (Alpine.start()), make sure Alpine.start() only runs once per browser session (if (!window.__alpineStarted) { window.__alpineStarted = true; Alpine.start() }) so navigating between pages never double-binds click handlers!

Complete project: a persistent Task Board in one HTML file

Let’s combine Alpine.data(), Alpine.store(), x-model, keyed x-for, keyboard shortcuts (Cmd+K / Ctrl+K), localStorage persistence, and toast feedback into one complete, standalone HTML file you can save as board.html and open right in your browser:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Alpine Task Board</title>
  <style>
    [x-cloak] { display: none !important; }
    body { font-family: system-ui, sans-serif; max-width: 38rem; margin: 2.5rem auto; padding: 0 1rem; color: #0f172a; }
    input, button { font: inherit; padding: 0.5rem 0.75rem; border-radius: 0.45rem; border: 1px solid #cbd5e1; }
    button { background: #f8fafc; cursor: pointer; }
    button.primary { background: #2563eb; color: #fff; border-color: #2563eb; }
    button.active { background: #0f172a; color: #fff; border-color: #0f172a; }
    .row { display: flex; gap: 0.5rem; margin-bottom: 1rem; }
    .row input { flex: 1; }
    ul { list-style: none; padding: 0; display: grid; gap: 0.5rem; }
    li { display: flex; align-items: center; gap: 0.65rem; padding: 0.65rem 0.8rem; border: 1px solid #e2e8f0; border-radius: 0.5rem; }
    li.done span { text-decoration: line-through; color: #64748b; }
    li span { flex: 1; }
    .toast { position: fixed; bottom: 1.25rem; right: 1.25rem; background: #0f172a; color: #fff; padding: 0.65rem 1rem; border-radius: 0.5rem; }
  </style>
  <script>
    document.addEventListener('alpine:init', () => {
      Alpine.store('toast', {
        text: '',
        open: false,
        timer: null,
        show(msg) {
          this.text = msg
          this.open = true
          clearTimeout(this.timer)
          this.timer = setTimeout(() => (this.open = false), 2200)
        },
      })

      Alpine.data('taskBoard', () => ({
        STORAGE_KEY: 'alpine-handbook-tasks',
        newTitle: '',
        query: '',
        filter: 'all',
        tasks: [],

        init() {
          const saved = localStorage.getItem(this.STORAGE_KEY)
          this.tasks = saved
            ? JSON.parse(saved)
            : [
                { id: 1, title: 'Learn x-data and x-model', done: true },
                { id: 2, title: 'Ship an Alpine.js app', done: false },
              ]
          this.$watch('tasks', (val) => {
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify(val))
          })
        },

        get visibleTasks() {
          const q = this.query.trim().toLowerCase()
          return this.tasks.filter((t) => {
            if (this.filter === 'open' && t.done) return false
            if (this.filter === 'done' && !t.done) return false
            return !q || t.title.toLowerCase().includes(q)
          })
        },

        get remaining() {
          return this.tasks.filter((t) => !t.done).length
        },

        addTask() {
          const title = this.newTitle.trim()
          if (!title) return
          this.tasks.unshift({ id: Date.now(), title, done: false })
          this.newTitle = ''
          Alpine.store('toast').show(`Added "${title}"`)
        },

        removeTask(id) {
          this.tasks = this.tasks.filter((t) => t.id !== id)
          Alpine.store('toast').show('Task removed')
        },
      }))
    })
  </script>
  <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.17.6/dist/cdn.min.js"></script>
</head>
<body>
  <main
    x-data="taskBoard"
    @keydown.cmd.k.window.prevent="$refs.search.focus()"
    @keydown.ctrl.k.window.prevent="$refs.search.focus()"
  >
    <h1>Tasks (<span x-text="remaining"></span> open)</h1>

    <form class="row" @submit.prevent="addTask()">
      <input x-model="newTitle" placeholder="Add a new task..." required />
      <button type="submit" class="primary">Add</button>
    </form>

    <div class="row">
      <input
        x-ref="search"
        type="search"
        x-model="query"
        placeholder="Filter tasks (Cmd+K)..."
      />
      <button type="button" :class="{ active: filter === 'all' }" @click="filter = 'all'">All</button>
      <button type="button" :class="{ active: filter === 'open' }" @click="filter = 'open'">Open</button>
      <button type="button" :class="{ active: filter === 'done' }" @click="filter = 'done'">Done</button>
    </div>

    <ul>
      <template x-for="task in visibleTasks" :key="task.id">
        <li :class="{ done: task.done }">
          <input type="checkbox" x-model="task.done" :aria-label="task.title" />
          <span x-text="task.title"></span>
          <button type="button" @click="removeTask(task.id)">Delete</button>
        </li>
      </template>
    </ul>

    <p x-show="visibleTasks.length === 0" x-cloak>No tasks match your filter.</p>
  </main>

  <div
    x-data
    x-show="$store.toast.open"
    x-transition
    x-cloak
    class="toast"
    role="status"
    aria-live="polite"
    x-text="$store.toast.text"
  ></div>
</body>
</html>

Open board.html in any browser: zero build tools, instant filtering, Cmd+K search focus, toast banners, and automatic persistence across reloads!

CSP builds, security, testing, and debugging

Two topics come up as soon as you ship Alpine to production: strict Content Security Policy (CSP) headers and automated tests.

Strict Content Security Policy (@alpinejs/csp)

Standard Alpine evaluates inline expressions like x-data="{ count: 0 }" or @click="count++" using JavaScript’s Function constructor.

That works everywhere by default, unless your server sends a strict Content-Security-Policy header without 'unsafe-eval':

Content-Security-Policy: default-src 'self'; script-src 'self'

With that header in place, the browser blocks new Function() and standard Alpine stops running. You often hit this in banking dashboards, healthcare portals, enterprise intranets, and browser extensions.

Alpine ships an official CSP-safe build called @alpinejs/csp that never calls eval() or new Function().

Load it from a CDN (or self-host the file under your own origin so 'self' allows it):

<script
  defer
  src="https://unpkg.com/@alpinejs/csp@3.17.6/dist/cdn.min.js"
></script>

Or install it with npm and import it in place of alpinejs:

npm install @alpinejs/csp
import Alpine from '@alpinejs/csp'

window.Alpine = Alpine
Alpine.start()

Because @alpinejs/csp does not run a full JavaScript evaluator on HTML attributes, you keep all logic inside Alpine.data() and reference plain property names, getters, and methods in HTML:

ExpressionStandard Alpine@alpinejs/csp
x-data="counter"AllowedAllowed
x-data="{ count: 0 }"AllowedBlocked
@click="increment"AllowedAllowed
@click="count++"AllowedBlocked
x-show="open" / x-show="!open"AllowedAllowed
x-show="count > 0"AllowedMove to a getter (hasItems)
x-text="user.name"AllowedAllowed

Here is a complete CSP-safe counter and toggle component with its logic in an external app.js file:

// public/app.js
document.addEventListener('alpine:init', () => {
  Alpine.data('cspCounter', () => ({
    count: 0,
    open: false,

    get atZero() {
      return this.count === 0
    },

    get label() {
      return this.open ? 'Hide history' : 'Show history'
    },

    increment() {
      this.count++
    },

    reset() {
      this.count = 0
    },

    toggle() {
      this.open = !this.open
    },
  }))
})

And the HTML stays free of inline scripts and inline expressions:

<div x-data="cspCounter">
  <p>Count: <strong x-text="count"></strong></p>

  <button type="button" @click="increment">Add 1</button>
  <button type="button" @click="reset" :disabled="atZero">
    Reset
  </button>

  <button type="button" @click="toggle" x-text="label"></button>
  <p x-show="open" x-cloak>
    Current total is <span x-text="count"></span>.
  </p>
</div>

Notice how moving count === 0 into get atZero() and the ternary into get label() makes the HTML shorter, keeps your CSP header strict, and lets you unit-test every method directly in Node.

Unit-testing Alpine.data() logic

When you extract component logic into plain factory functions registered with Alpine.data(), you can unit-test every state transition directly in Vitest or node:test with zero browser needed:

// counter.js
export function createCounter(start = 0) {
  return {
    count: start,
    increment() {
      this.count += 1
    },
    reset() {
      this.count = start
    },
  }
}
// counter.test.js
import assert from 'node:assert/strict'
import test from 'node:test'
import { createCounter } from './counter.js'

test('counter increments and resets', () => {
  const counter = createCounter(5)
  counter.increment()
  assert.equal(counter.count, 6)
  counter.reset()
  assert.equal(counter.count, 5)
})

Debugging common Alpine pitfalls

If console.log(this.tasks) prints a cryptic Proxy(Array) in DevTools, unwrap it cleanly with Alpine.raw(this.tasks) (or console.log(JSON.parse(JSON.stringify(this.tasks)))).

SymptomUsual causeFast fix
Hidden dropdown flashes on page loadMissing x-cloak or [x-cloak] CSS ruleAdd [x-cloak] { display: none !important; } and x-cloak
x-if or x-for throws an errorPut directly on <div> or <template> had two root tagsAlways put on <template> with one single root element
$refs.input.focus() does nothingTried focusing before x-show updated the DOMWrap inside $nextTick(() => $refs.input.focus())
Alpine.data() component is not definedScript registered after Alpine.start() or missed alpine:initRegister inside alpine:init listener or before Alpine.start()
Server-rendered input value gets wiped to ""x-model initialized with empty stringUse x-model.fill to read the HTML value attribute
Plugin directive like $persist failsPlugin <script> loaded after core alpinejsPut every plugin <script defer> tag before core Alpine

Common beginner Alpine.js mistakes

Keep an eye out for these five classic Alpine hiccups when starting out:

  • Forgetting x-cloak CSS. Without [x-cloak] { display: none !important; } in your stylesheet, dropdowns and modals flash visibly for a split second before Alpine finishes loading.
  • Putting x-if or x-for directly on a <div> or <li>. Both x-if and x-for must sit on a <template> tag containing one root element inside.
  • Forgetting x-for needs a unique :key. Whenever items can be added, sorted, or deleted, add :key="item.id" on <template x-for="item in items" :key="item.id">.
  • Forgetting .prevent on form submit. Write @submit.prevent="save()" so the browser does not reload the page before your Alpine handler runs.
  • Quote collisions inside HTML attributes. If an attribute uses double quotes (@click="..."), wrap JavaScript strings inside it in single quotes (tab = 'home').

Hands-on beginner Alpine.js exercises (with solutions)

Reading examples gets you halfway there. Building small widgets yourself makes every directive stick.

Try building each of these ten progressive exercises in a blank HTML file before peeking at the working solution underneath.

Exercise 1: Bounded counter with min, max, and reset

Build a counter that starts at 0, increments by 1, decrements by 1, never goes below 0 or above 10, and disables each button when it hits its limit.

<div
  x-data="{
    count: 0,
    min: 0,
    max: 10
  }"
>
  <button
    type="button"
    @click="if (count > min) count--"
    :disabled="count <= min"
  >
    -
  </button>

  <strong x-text="count"></strong>

  <button
    type="button"
    @click="if (count < max) count++"
    :disabled="count >= max"
  >
    +
  </button>

  <button
    type="button"
    @click="count = 0"
    :disabled="count === 0"
  >
    Reset
  </button>
</div>

Binding :disabled to the exact boundary checks keeps the UI honest even before anyone clicks.

Exercise 2: Live search filter over an array

Filter a list of fruits as the user types, ignoring letter case, and show a fallback message when nothing matches.

<div
  x-data="{
    q: '',
    fruits: ['Banana', 'Pear', 'Apple', 'Mango', 'Kiwi'],
    get filtered() {
      const term = this.q.trim().toLowerCase()
      return this.fruits.filter((f) =>
        f.toLowerCase().includes(term)
      )
    }
  }"
>
  <input
    type="search"
    x-model="q"
    placeholder="Filter fruit..."
  />

  <ul>
    <template x-for="fruit in filtered" :key="fruit">
      <li x-text="fruit"></li>
    </template>
  </ul>

  <p x-show="filtered.length === 0">No matching fruit.</p>
</div>

Putting the filter inside a getter keeps this.fruits untouched while recalculating whenever q changes.

Exercise 3: Dark-mode toggle saved in localStorage

Toggle a dark class on <html>, remember the choice across reloads in localStorage, and update aria-pressed on the button.

<button
  type="button"
  x-data="{
    dark: localStorage.getItem('theme') === 'dark',
    apply() {
      document.documentElement.classList.toggle('dark', this.dark)
      localStorage.setItem('theme', this.dark ? 'dark' : 'light')
    },
    toggle() {
      this.dark = !this.dark
      this.apply()
    }
  }"
  x-init="apply()"
  @click="toggle()"
  :aria-pressed="dark"
  x-text="dark ? 'Switch to light' : 'Switch to dark'"
></button>

Calling apply() inside x-init makes sure the saved class is applied right when the page loads.

Exercise 4: Interactive 5-star rating with hover preview

Render five stars with x-for="n in 5", highlight stars as the mouse hovers over them, lock in the choice on click, and allow clearing back to 0.

<div
  x-data="{
    rating: 0,
    hover: 0,
    get activeStars() {
      return this.hover || this.rating
    }
  }"
  @mouseleave="hover = 0"
>
  <template x-for="n in 5" :key="n">
    <button
      type="button"
      @mouseenter="hover = n"
      @click="rating = n"
      :aria-label="'Rate ' + n + ' out of 5'"
      :style="{
        color: n <= activeStars ? '#eab308' : '#cbd5e1',
        fontSize: '1.5rem',
        background: 'none',
        border: 0,
        cursor: 'pointer'
      }"
    >
      ★
    </button>
  </template>

  <p>
    Rating: <strong x-text="rating"></strong> / 5
    <button
      type="button"
      x-show="rating > 0"
      @click="rating = 0"
    >
      Clear
    </button>
  </p>
</div>

Separating hover from rating lets the preview reset back to the locked score the moment the pointer leaves.

Exercise 5: Tip and bill splitter calculator

Take a bill amount, tip percentage presets, and number of diners using x-model.number, then compute the tip and per-person total live.

<div
  x-data="{
    bill: 60,
    tipPct: 15,
    people: 2,
    get tipAmount() {
      return (this.bill || 0) * (this.tipPct / 100)
    },
    get total() {
      return (this.bill || 0) + this.tipAmount
    },
    get perPerson() {
      return this.people > 0 ? this.total / this.people : 0
    }
  }"
>
  <label>
    Bill ($)
    <input type="number" x-model.number="bill" min="0" step="0.5" />
  </label>

  <div>
    <template x-for="pct in [10, 15, 20]" :key="pct">
      <button
        type="button"
        @click="tipPct = pct"
        :disabled="tipPct === pct"
        x-text="pct + '%'"
      ></button>
    </template>
  </div>

  <label>
    People
    <input type="number" x-model.number="people" min="1" />
  </label>

  <p>Tip: $<strong x-text="tipAmount.toFixed(2)"></strong></p>
  <p>Total: $<strong x-text="total.toFixed(2)"></strong></p>
  <p>
    Per person:
    $<strong x-text="perPerson.toFixed(2)"></strong>
  </p>
</div>

Using .number avoids string math bugs, and this.bill || 0 guards against an empty input returning NaN.

Exercise 6: Tag input with Enter and Backspace

Let users type a tag and press Enter to add it (skipping blanks and duplicates), click x to remove a tag, or press Backspace on an empty box to remove the last tag.

<div
  x-data="{
    input: '',
    tags: ['alpine', 'html'],
    addTag() {
      const tag = this.input.trim().toLowerCase()
      if (!tag || this.tags.includes(tag)) {
        this.input = ''
        return
      }
      this.tags.push(tag)
      this.input = ''
    },
    removeTag(tag) {
      this.tags = this.tags.filter((t) => t !== tag)
    },
    removeLast() {
      if (!this.input && this.tags.length > 0) {
        this.tags.pop()
      }
    }
  }"
>
  <div>
    <template x-for="tag in tags" :key="tag">
      <span>
        <span x-text="tag"></span>
        <button
          type="button"
          @click="removeTag(tag)"
          :aria-label="'Remove ' + tag"
        >
          x
        </button>
      </span>
    </template>
  </div>

  <input
    type="text"
    x-model="input"
    @keydown.enter.prevent="addTag()"
    @keydown.backspace="removeLast()"
    placeholder="Add tag and press Enter"
  />
</div>

Adding .prevent on @keydown.enter stops the input from submitting an outer <form> by accident.

Exercise 7: Countdown timer with Start, Pause, Reset, and cleanup

Build a 2-minute timer that formats MM:SS, stops automatically at 00:00, and clears its interval inside destroy().

<div
  x-data="{
    seconds: 120,
    running: false,
    timerId: null,
    get formatted() {
      const m = String(Math.floor(this.seconds / 60)).padStart(2, '0')
      const s = String(this.seconds % 60).padStart(2, '0')
      return `${m}:${s}`
    },
    start() {
      if (this.running || this.seconds === 0) return
      this.running = true
      this.timerId = setInterval(() => {
        if (this.seconds > 0) {
          this.seconds--
        } else {
          this.pause()
        }
      }, 1000)
    },
    pause() {
      this.running = false
      clearInterval(this.timerId)
      this.timerId = null
    },
    reset() {
      this.pause()
      this.seconds = 120
    },
    destroy() {
      this.pause()
    }
  }"
>
  <p><strong x-text="formatted"></strong></p>
  <button
    type="button"
    @click="running ? pause() : start()"
    x-text="running ? 'Pause' : 'Start'"
  ></button>
  <button type="button" @click="reset()">Reset</button>
</div>

Always guard start() with if (this.running) return so double-clicking never spawns two intervals at once.

Exercise 8: Launch checklist with live progress bar

Track completed checklist items in an array, display a percentage progress bar with :style, and provide “Check all” and “Clear” buttons.

<div
  x-data="{
    steps: [
      'Add x-cloak CSS rule',
      'Test Escape key on modals',
      'Check keyboard Tab order',
      'Verify production CSP header'
    ],
    done: [],
    get percent() {
      return Math.round((this.done.length / this.steps.length) * 100)
    }
  }"
>
  <div style="background: #e2e8f0; height: 10px;">
    <div
      style="background: #16a34a; height: 100%;"
      :style="{ width: percent + '%' }"
    ></div>
  </div>

  <p><strong x-text="percent + '%'"></strong> complete</p>

  <button type="button" @click="done = [...steps]">Check all</button>
  <button type="button" @click="done = []">Clear</button>

  <ul>
    <template x-for="step in steps" :key="step">
      <li>
        <label>
          <input type="checkbox" :value="step" x-model="done" />
          <span x-text="step"></span>
        </label>
      </li>
    </template>
  </ul>
</div>

Cloning with [...steps] when checking all avoids linking done directly to the same array reference as steps.

Exercise 9: Undoable shopping list

When a user deletes an item, remember the item and its original index for 5 seconds so an “Undo” banner can put it right back where it belonged.

<div
  x-data="{
    items: [
      { id: 1, name: 'Coffee beans' },
      { id: 2, name: 'Oat milk' },
      { id: 3, name: 'Sourdough bread' }
    ],
    lastDeleted: null,
    undoTimer: null,
    remove(index) {
      const [item] = this.items.splice(index, 1)
      this.lastDeleted = { item, index }
      clearTimeout(this.undoTimer)
      this.undoTimer = setTimeout(() => {
        this.lastDeleted = null
      }, 5000)
    },
    undo() {
      if (!this.lastDeleted) return
      const { item, index } = this.lastDeleted
      this.items.splice(index, 0, item)
      this.lastDeleted = null
      clearTimeout(this.undoTimer)
    },
    destroy() {
      clearTimeout(this.undoTimer)
    }
  }"
>
  <ul>
    <template x-for="(item, idx) in items" :key="item.id">
      <li>
        <span x-text="item.name"></span>
        <button type="button" @click="remove(idx)">Remove</button>
      </li>
    </template>
  </ul>

  <div x-show="lastDeleted" x-cloak role="status">
    Removed <strong x-text="lastDeleted?.item.name"></strong>.
    <button type="button" @click="undo()">Undo</button>
  </div>
</div>

Saving both item and index lets splice(index, 0, item) restore the row in its exact original slot.

Exercise 10: Keyboard-navigable tabs synced to the URL hash

Read window.location.hash on boot so links like /page#specs open the right tab immediately, update the hash on tab switch, and support Left and Right arrow keys on the tab list.

<div
  x-data="{
    tabs: ['overview', 'specs', 'reviews'],
    active: 'overview',
    syncFromHash() {
      const hash = window.location.hash.replace('#', '')
      if (this.tabs.includes(hash)) this.active = hash
    },
    select(name) {
      this.active = name
      history.replaceState(null, '', '#' + name)
    },
    step(delta) {
      const i = this.tabs.indexOf(this.active)
      const next = (i + delta + this.tabs.length) % this.tabs.length
      this.select(this.tabs[next])
    }
  }"
  x-init="syncFromHash()"
  @hashchange.window="syncFromHash()"
>
  <div
    role="tablist"
    @keydown.arrow-right.prevent="step(1)"
    @keydown.arrow-left.prevent="step(-1)"
  >
    <template x-for="name in tabs" :key="name">
      <button
        type="button"
        role="tab"
        :aria-selected="active === name"
        @click="select(name)"
        x-text="name"
      ></button>
    </template>
  </div>

  <div role="tabpanel" x-show="active === 'overview'">
    Product overview content.
  </div>
  <div role="tabpanel" x-show="active === 'specs'" x-cloak>
    Technical specifications content.
  </div>
  <div role="tabpanel" x-show="active === 'reviews'" x-cloak>
    Customer reviews content.
  </div>
</div>

Using history.replaceState() updates the URL hash cleanly for sharing without polluting the user’s Back button history on every tab click.

Quick reference: directives and magic properties

Core directives

DirectivePurposeExample
x-dataDeclares component state and methodsx-data="{ open: false }"
x-on (@)Listens for DOM events@click="open = !open"
x-bind (:)Dynamically binds HTML attributes or classes:disabled="loading"
x-showToggles display: nonex-show="open"
x-ifAdds/removes DOM subtree (on <template>)<template x-if="ready">
x-forLoops over an array (on <template>)<template x-for="item in items" :key="item.id">
x-modelTwo-way form input bindingx-model.trim="email"
x-textSets safe escaped textContentx-text="count"
x-htmlSets raw innerHTML (trusted HTML only!)x-html="safeMarkup"
x-transitionSmooth show/hide CSS transitionsx-show="open" x-transition
x-cloakHides element until Alpine initializesx-cloak
x-initRuns once on component mountx-init="load()"
x-effectRe-runs whenever referenced state changesx-effect="sync()"
x-refRegisters element in $refsx-ref="input"
x-ignoreTells Alpine to skip a DOM subtree<div x-ignore>

Built-in magic properties

MagicWhat it gives you
$elThe current DOM element
$refsObject mapping x-ref names to DOM elements
$storeAccess to global Alpine.store() state
$eventCurrent native DOM event inside @event handlers
$dispatchFires a custom bubbling DOM event
$nextTickRuns a callback after Alpine finishes patching the DOM
$watchWatches a property for changes
$idGenerates scoped unique IDs for accessible labels
$rootNearest parent element carrying x-data
$dataCurrent reactive scope object

Where to go from here

You now know everything you need to build snappy, accessible client-side interactions with Alpine.js while keeping your web stack small and pleasant to work in.

Next time you need a dropdown, modal, live filter, or interactive form on a server-rendered page, try reaching for Alpine before spinning up a full SPA bundler.

If you want to pair Alpine with server-driven HTML updates, read my free htmx Handbook, HTML Forms Handbook, and JavaScript Handbook.

Want me to talk about your product? You can sponsor this site.

Related posts about alpine: