Frontend

Alpine.js: Lightweight JavaScript Framework

Mayur Dabhi
Mayur Dabhi
June 14, 2026
14 min read

You've got a server-rendered app, maybe Laravel with Blade, and the designer wants a dropdown in the navbar, a confirm modal, and some tabs on the settings page. Writing that in vanilla JS means a pile of querySelector calls and event listeners that nobody wants to maintain. Pulling in React or Vue for three widgets means a build pipeline, a mount point, and a second way of rendering HTML.

Alpine.js sits in between. There's no compiler, no virtual DOM, and no component file format. It scans your HTML for x-* attributes after the page loads and wires up reactive behavior right there in the markup. In this post I'll cover installation (CDN, npm, and Laravel), the core directives, three components you can paste into a project, global state with Alpine.store(), the official plugins, and where Alpine stops being the right choice.

Some Background

Alpine.js was created by Caleb Porzio, who also wrote Laravel Livewire, and it's the "A" in the Laravel TALL stack (Tailwind, Alpine.js, Laravel, Livewire). Version 3, released in 2021, added the plugin system and the global store. It's around 15kb minified and gzipped.

Where Alpine.js Fits

The sweet spot is when you need more than CSS can do, but a full React or Vue app would be overkill. What you get:

Alpine.js vs Other Frameworks

Feature Alpine.js React Vue.js jQuery
Bundle Size (gzipped) ~15kb ~45kb + ReactDOM ~130kb ~35kb ~30kb
Build Step Required No Yes (JSX) Optional No
Virtual DOM No Yes Yes No
Reactivity System Proxy-based useState / hooks Proxy-based Manual DOM
Learning Curve Low (hours) High (weeks) Medium (days) Low
Best For Server-side apps, sprinkles Large SPAs, complex UIs SPAs, medium complexity DOM manipulation, legacy
Component Model Inline x-data scopes JSX components Single File Components Plugins / closures

Installation and Setup

The CDN tag is the quickest way to try it. If you already have a bundler, use npm.

1

Via CDN (Recommended for Getting Started)

Add a single script tag to your HTML <head>. Use defer so it runs after the HTML is parsed.

index.html: CDN Install
<!-- Alpine.js v3 via CDN -->
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>

<!-- Now use Alpine anywhere in your HTML -->
<div x-data="{ open: false }">
    <button @click="open = !open">Toggle</button>
    <div x-show="open">Hello Alpine.js!</div>
</div>
2

Via npm (For Build Pipelines)

Install via npm when you want to use plugins, tree-shaking, or integrate with Vite/Webpack.

Terminal: npm Install
npm install alpinejs
app.js: npm Entry Point
import Alpine from 'alpinejs'

// Register plugins before starting Alpine
// import Collapse from '@alpinejs/collapse'
// Alpine.plugin(Collapse)

window.Alpine = Alpine
Alpine.start()
3

With Laravel and Vite

Laravel ships with Vite and already has Alpine.js in resources/js/app.js when you scaffold with Breeze or Jetstream.

resources/js/app.js: Laravel Integration
import './bootstrap';
import Alpine from 'alpinejs';

window.Alpine = Alpine;
Alpine.start();

// In Blade templates, Alpine is available automatically
// after running: npm run dev (or npm run build for production)
The TALL Stack

Laravel developers often use Alpine.js as part of the TALL stack: Tailwind CSS + Alpine.js + Laravel + Livewire. Alpine.js handles client-side UI state (dropdowns, modals, tabs) while Livewire handles server-driven reactivity (form submission, live search, real-time updates).

Two Setup Gotchas

Content flashes on load: anything hidden with x-show is visible until Alpine boots, so a dropdown or modal can flicker on every page load. Add x-cloak to the element and the CSS rule [x-cloak] { display: none !important; }. Alpine removes the attribute once it initializes.

Livewire 3 already includes Alpine: if you also import alpinejs in app.js, you'll see "Detected multiple instances of Alpine running" in the console and things like $wire or plugins behave oddly. Remove your own import and let Livewire load it.

The Core Directives

Directives are the x-* attributes you add to elements. Alpine v3 has around 18 of them, but these are the ones you'll write every day:

x-data is the foundation of every Alpine component. It declares a reactive JavaScript object that all child elements can access. x-init runs code when the component mounts.

<!-- Basic x-data -->
<div x-data="{ count: 0, name: 'World' }">
    <p x-text="'Hello, ' + name"></p>
    <button @click="count++">Count: <span x-text="count"></span></button>
</div>

<!-- x-data can reference a function for complex components -->
<div x-data="counter()">
    <button @click="increment">Count: <span x-text="count"></span></button>
</div>

<script>
function counter() {
    return {
        count: 0,
        increment() {
            this.count++
        }
    }
}
</script>

<!-- x-init runs when the component initializes -->
<div x-data="{ users: [] }" x-init="users = await (await fetch('/api/users')).json()">
    <template x-for="user in users" :key="user.id">
        <p x-text="user.name"></p>
    </template>
</div>

x-show toggles an element's CSS display property. The element stays in the DOM. x-if actually removes and recreates the element, so use it for heavy markup you don't want sitting in the page.

<!-- x-show: toggles display:none (element stays in DOM) -->
<div x-data="{ open: false }">
    <button @click="open = !open">Toggle Panel</button>

    <div x-show="open">
        This panel is shown/hidden with CSS.
    </div>

    <!-- x-show with transitions -->
    <div x-show="open"
         x-transition:enter="transition ease-out duration-300"
         x-transition:enter-start="opacity-0 transform scale-90"
         x-transition:enter-end="opacity-100 transform scale-100"
         x-transition:leave="transition ease-in duration-300"
         x-transition:leave-start="opacity-100 transform scale-100"
         x-transition:leave-end="opacity-0 transform scale-90">
        Animated panel!
    </div>
</div>

<!-- x-if: removes element from DOM completely -->
<div x-data="{ loggedIn: false }">
    <template x-if="loggedIn">
        <div>Welcome back! <!-- Only mounted when loggedIn --></div>
    </template>
    <template x-if="!loggedIn">
        <div>Please log in.</div>
    </template>
</div>

x-for renders a list of elements by iterating over an array. It must be used on a <template> tag and requires a unique :key for efficient DOM updates.

<div x-data="{
    todos: [
        { id: 1, text: 'Learn Alpine.js', done: true },
        { id: 2, text: 'Build something cool', done: false },
        { id: 3, text: 'Ship to production', done: false }
    ],
    newTodo: ''
}">
    <!-- Input to add todos -->
    <input x-model="newTodo" @keyup.enter="
        todos.push({ id: Date.now(), text: newTodo, done: false });
        newTodo = ''
    " placeholder="Add todo...">

    <!-- Render the list -->
    <ul>
        <template x-for="todo in todos" :key="todo.id">
            <li>
                <input type="checkbox" x-model="todo.done">
                <span :class="todo.done ? 'line-through opacity-50' : ''"
                      x-text="todo.text"></span>
                <button @click="todos = todos.filter(t => t.id !== todo.id)">
                    &times;
                </button>
            </li>
        </template>
    </ul>

    <!-- Show count -->
    <p x-text="todos.filter(t => !t.done).length + ' remaining'"></p>
</div>

x-model creates two-way data binding between form inputs and your Alpine data. It works with text inputs, checkboxes, radio buttons, selects, and textareas.

<div x-data="{
    name: '',
    email: '',
    role: 'developer',
    subscribe: false,
    skills: []
}">
    <!-- Text input -->
    <input x-model="name" type="text" placeholder="Your name">
    <p x-text="'Hello, ' + (name || 'stranger') + '!'"></p>

    <!-- Email with lazy modifier (only syncs on blur) -->
    <input x-model.lazy="email" type="email">

    <!-- Number input with .number modifier -->
    <input x-model.number="age" type="number">

    <!-- Select dropdown -->
    <select x-model="role">
        <option value="developer">Developer</option>
        <option value="designer">Designer</option>
        <option value="manager">Manager</option>
    </select>

    <!-- Checkbox -->
    <input x-model="subscribe" type="checkbox">
    <span x-text="subscribe ? 'Subscribed' : 'Not subscribed'"></span>

    <!-- Multiple checkboxes bind to array -->
    <input x-model="skills" value="js" type="checkbox"> JavaScript
    <input x-model="skills" value="php" type="checkbox"> PHP
    <p x-text="'Skills: ' + skills.join(', ')"></p>
</div>

Event Handling and Attribute Binding

Alpine.js uses x-on (shorthand: @) for event listeners and x-bind (shorthand: :) for dynamic attribute binding. These two directives handle the vast majority of interactive behavior:

x-on and x-bind Examples
<div x-data="{ active: false, color: 'blue', count: 0 }">

    <!-- x-on / @ : event listeners -->
    <button @click="active = !active">Toggle</button>
    <button @click.prevent="submitForm()">Submit (no page reload)</button>
    <input @keyup.enter="search()">              <!-- Only fires on Enter key -->
    <input @keyup.escape="clear()">             <!-- Only fires on Escape key -->
    <button @click.once="doOnce()">Once only</button>  <!-- Fires once then removes listener -->
    <div @mouseover.throttle.500ms="track()">Throttled</div>
    <input @input.debounce.300ms="liveSearch()">  <!-- Debounced search -->

    <!-- x-bind / : : attribute binding -->
    <div :class="active ? 'bg-blue-500' : 'bg-gray-200'">...</div>

    <!-- Bind multiple classes as object -->
    <div :class="{ 'font-bold': active, 'text-red-500': count > 10 }">...</div>

    <!-- Bind styles -->
    <div :style="{ color: color, fontSize: count + 'px' }">Dynamic style</div>

    <!-- Bind any attribute -->
    <button :disabled="count >= 10">Add (max 10)</button>
    <img :src="user.avatar" :alt="user.name">
    <a :href="'/user/' + userId">Profile</a>
</div>
x-data Reactive Proxy watches State Change { count: 1 } triggers DOM Update x-text, x-show, : renders 👁 UI user interaction (@click, @input) updates state

The Alpine.js reactivity cycle: state changes propagate to the DOM automatically

x-show vs x-if

Use x-show when you toggle an element frequently (it just adds/removes display:none, which is fast). Use x-if when the element is expensive to render and you want to completely remove it from the DOM. x-if only works on a <template> tag, and so does x-for. Put either one on a regular <div> and it won't render what you expect.

Building Real-World Components

Here are three components that show up in almost every admin panel or dashboard. Each one is self-contained, so you can paste it into a Blade view and adjust the classes.

1. Dropdown Menu

Dropdown Component
<div x-data="{ open: false }" class="relative">
    <!-- Trigger -->
    <button
        @click="open = !open"
        @keydown.escape.window="open = false"
        :aria-expanded="open"
        class="btn">
        Options
        <svg :class="{ 'rotate-180': open }" ...></svg>
    </button>

    <!-- Dropdown panel -->
    <div
        x-show="open"
        x-transition
        @click.outside="open = false"
        class="absolute top-full mt-2 w-48 bg-white shadow-lg rounded-lg z-10">
        <a href="/profile" class="block px-4 py-2 hover:bg-gray-100">Profile</a>
        <a href="/settings" class="block px-4 py-2 hover:bg-gray-100">Settings</a>
        <hr>
        <button @click="logout()" class="block w-full text-left px-4 py-2 text-red-600">
            Logout
        </button>
    </div>
</div>

2. Modal Dialog

Modal Component
<div x-data="{ showModal: false }">
    <!-- Open button -->
    <button @click="showModal = true">Open Modal</button>

    <!-- Backdrop + Modal -->
    <div
        x-show="showModal"
        x-transition.opacity
        @keydown.escape.window="showModal = false"
        class="fixed inset-0 z-50 flex items-center justify-center">

        <!-- Backdrop -->
        <div
            class="absolute inset-0 bg-black bg-opacity-50"
            @click="showModal = false">
        </div>

        <!-- Modal panel -->
        <div
            x-show="showModal"
            x-transition:enter="transition ease-out duration-200"
            x-transition:enter-start="opacity-0 scale-95"
            x-transition:enter-end="opacity-100 scale-100"
            x-transition:leave="transition ease-in duration-150"
            x-transition:leave-start="opacity-100 scale-100"
            x-transition:leave-end="opacity-0 scale-95"
            class="relative bg-white rounded-xl shadow-xl p-8 max-w-md w-full mx-4">

            <h2 class="text-xl font-bold mb-4">Confirm Action</h2>
            <p class="text-gray-600 mb-6">Are you sure you want to do this?</p>

            <div class="flex gap-4 justify-end">
                <button @click="showModal = false" class="btn-secondary">Cancel</button>
                <button @click="confirmAction(); showModal = false" class="btn-primary">
                    Confirm
                </button>
            </div>
        </div>
    </div>
</div>

3. Character Counter with Live Validation

Character Counter
<div x-data="{
    bio: '',
    maxLength: 160,
    get remaining() { return this.maxLength - this.bio.length },
    get isOverLimit() { return this.bio.length > this.maxLength },
    get isNearLimit() { return this.remaining < 20 && !this.isOverLimit }
}">
    <textarea
        x-model="bio"
        rows="4"
        placeholder="Write your bio..."
        :class="{
            'border-red-500': isOverLimit,
            'border-yellow-400': isNearLimit,
            'border-gray-300': !isNearLimit && !isOverLimit
        }"
        class="w-full p-3 border rounded-lg resize-none">
    </textarea>

    <div class="flex justify-between mt-2 text-sm">
        <span
            x-text="isOverLimit ? 'Too long by ' + Math.abs(remaining) + ' chars' : ''"
            class="text-red-500">
        </span>
        <span
            :class="{
                'text-red-500': isOverLimit,
                'text-yellow-500': isNearLimit,
                'text-gray-400': !isNearLimit && !isOverLimit
            }"
            x-text="remaining + ' remaining'">
        </span>
    </div>

    <button
        :disabled="isOverLimit || bio.length === 0"
        class="mt-4 btn-primary">
        Save Bio
    </button>
</div>
HTML Page (Blade / HTML) Dropdown x-data="{ open:false }" @click → open=!open x-show="open" Modal x-data="{ show:false }" @click.outside close x-transition animate Counter x-data computed x-model two-way :class dynamic

Each x-data scope is an isolated component that manages its own state

Magic Properties and Global State

Inside any Alpine expression you get a handful of $-prefixed "magic" properties. They cover the things you'd otherwise write extra JavaScript for: grabbing an element, reading the event, talking to other components, waiting for the DOM.

Magic Properties Overview
<div x-data="{ value: '' }" x-init="$watch('value', val => console.log('changed:', val))">

    <!-- $el: the current DOM element -->
    <button @click="$el.textContent = 'Clicked!'">Click me</button>

    <!-- $refs: access elements by x-ref -->
    <input x-ref="myInput" type="text">
    <button @click="$refs.myInput.focus()">Focus Input</button>

    <!-- $event: the native browser event -->
    <input @keyup="console.log($event.key)">

    <!-- $dispatch: emit custom events to parent components -->
    <button @click="$dispatch('notify', { message: 'Hello!', type: 'success' })">
        Send Notification
    </button>

    <!-- Parent listens to the event -->
    <div @notify.window="showToast($event.detail.message)"></div>

    <!-- $nextTick: wait for DOM to update -->
    <button @click="value = 'updated'; $nextTick(() => console.log($refs.output.textContent))">
        Update & Read
    </button>
    <span x-ref="output" x-text="value"></span>

    <!-- $watch: reactively watch a property -->
    <!-- (set up in x-init above) -->
    <input x-model="value" placeholder="Type to trigger watcher">
</div>

Global State with Alpine.store()

When two unrelated components need the same data (an "add to cart" button and the cart count in the navbar, say), use a global store. For the size of app Alpine is meant for, you won't miss Vuex or Redux.

Global Store with Alpine.store()
<script>
// Register the store before Alpine starts
document.addEventListener('alpine:init', () => {
    Alpine.store('cart', {
        items: [],
        get count() { return this.items.length },
        get total() { return this.items.reduce((sum, item) => sum + item.price, 0) },

        addItem(product) {
            const existing = this.items.find(i => i.id === product.id)
            if (existing) {
                existing.qty++
            } else {
                this.items.push({ ...product, qty: 1 })
            }
        },

        removeItem(id) {
            this.items = this.items.filter(i => i.id !== id)
        }
    })
})
</script>

<!-- Component A: Add to cart button (anywhere on the page) -->
<div x-data>
    <button @click="$store.cart.addItem({ id: 1, name: 'Widget', price: 9.99 })">
        Add to Cart
    </button>
</div>

<!-- Component B: Cart icon in navbar (completely separate component) -->
<div x-data>
    <span>Cart (<span x-text="$store.cart.count"></span> items)</span>
    <span x-text="'$' + $store.cart.total.toFixed(2)"></span>
</div>

Official Alpine.js Plugins

The official plugins are small packages that add a directive or magic property each. You install only the ones you need, and you register them with Alpine.plugin() before calling Alpine.start().

Plugin Package What It Adds
Collapse @alpinejs/collapse Smooth animated element collapse with x-collapse
Focus @alpinejs/focus Focus trapping inside modals and dialogs with x-trap
Intersect @alpinejs/intersect Intersection Observer callbacks with x-intersect
Persist @alpinejs/persist Persist state to localStorage with $persist
Sort @alpinejs/sort Drag-and-drop sorting with x-sort
Anchor @alpinejs/anchor Position elements relative to others with x-anchor
Mask @alpinejs/mask Input masking for phone numbers, dates, etc. with x-mask
Persist Plugin: Remember Dark Mode
<script>
import Alpine from 'alpinejs'
import Persist from '@alpinejs/persist'
import Focus from '@alpinejs/focus'

Alpine.plugin(Persist)
Alpine.plugin(Focus)

Alpine.start()
</script>

<!-- $persist automatically saves to localStorage -->
<div x-data="{ darkMode: $persist(false) }">
    <button @click="darkMode = !darkMode">
        <span x-text="darkMode ? '☀ Light' : '🌙 Dark'"></span>
    </button>
    <!-- darkMode preference survives page reloads -->
</div>

<!-- x-trap keeps focus inside modal (great for accessibility) -->
<div x-data="{ open: false }">
    <button @click="open = true">Open Modal</button>
    <div x-show="open" x-trap="open">
        <!-- Tab key stays within this element when open=true -->
        <button @click="open = false">Close</button>
        <input type="text" placeholder="Focus is trapped here">
    </div>
</div>

When I'd Use Alpine.js (and When I Wouldn't)

Picking Alpine for the wrong project is expensive to undo, because by the time it hurts, the logic is spread across dozens of templates. Here's roughly how I'd decide:

Scenario Recommendation Why
Server-rendered app (Laravel, Rails, Django) needing dropdowns/modals Alpine.js No build step, minimal overhead, works inside Blade/ERB templates
Complex SPA with rich client-side routing React or Vue.js Alpine.js has no router and wasn't designed for SPAs
Real-time features with server push Alpine.js + Livewire Livewire handles server-side reactivity, Alpine handles local UI state
Legacy PHP/Rails site needing sprinkles of JS Alpine.js Drop in via CDN, no npm, no rebuild needed
Team with deep React expertise React / Next.js Don't introduce Alpine.js for novelty. Use what your team knows.
Marketing site or blog with light interactivity Alpine.js Tiny bundle, fast load, fine for accordion FAQs and image galleries
Dashboard with complex data tables and charts Vue.js or React Alpine.js state management gets unwieldy at scale without components

Signs You've Outgrown Alpine

  • Your x-data strings are 40 lines long: move them into Alpine.data('name', () => ({...})) in a JS file. If even that file keeps growing, you're writing an app, not sprinkles.
  • Everything goes through the store: one or two stores are fine. When most components read and write shared state, a framework with real components and dev tools will be easier to debug.
  • You're rendering big lists client-side: x-for over thousands of rows gets sluggish because there's no virtual DOM or windowing. Paginate on the server instead.
  • You need SEO-friendly content from JS: Alpine runs after the page loads, so anything it renders isn't in the initial HTML. Render it in Blade and let Alpine only handle the behavior.

For server-rendered apps (Laravel, Rails, Django, WordPress) that need dropdowns, modals, tabs, and some form logic, Alpine is usually the least amount of JavaScript that gets the job done. Just don't skip accessibility because it's "only a dropdown": use the Focus plugin's x-trap for modals, and keep aria-expanded in sync like the dropdown example above. If your page is mostly client-side state, though, start with Vue or React from day one instead of migrating later.

Alpine.js JavaScript Frontend Reactive Laravel TALL Stack Lightweight
Mayur Dabhi

Mayur Dabhi

Full Stack Developer with 5+ years of experience building scalable web applications with Laravel, React, and Node.js.